What is the output of the following Node.js code?
4 phương ánCó giải thích
const fs = require('fs');
const util = require('util');
const readFile = util.promisify(fs.readFile);
async function main() {
try {
const data = await readFile('config.json', 'utf8');
console.log('Success:', data);
} catch (err) {
console.log('Error:', err.message);
}
console.log('Done');
}
main();Assume 'config.json' does NOT exist.
Các phương án trả lời
Chọn một phương ánLời giảiChọn phương án để mở
Đáp án đúng: "Error: ENOENT: no such file or directory, open 'config.json' Done". Lần theo mã: util.promisify biến fs.readFile kiểu callback thành hàm trả về Promise; trong main, await readFile('config.json', 'utf8') chờ Promise đó, và vì tệp không tồn tại nên Promise bị reject với lỗi mã ENOENT, message là ENOENT: no such file or directory, open 'config.json'; await ném lỗi vào khối catch, in dòng Error kèm message, rồi chạy tiếp ra ngoài try/catch in Done, nên hai dòng xuất hiện theo thứ tự lỗi trước, Done sau. "Success: undefined Done" sai vì dòng Success chỉ chạy khi đọc tệp thành công, ở đây readFile thất bại nên lệnh đó bị bỏ qua. "Done Error: ENOENT: no such file or directory" sai thứ tự: await làm main dừng chờ, còn console.log('Done') đứng sau toàn bộ try/catch nên không thể in trước lỗi. "Throws an unhandled promise rejection" sai vì lỗi đã được bắt bởi catch bên trong hàm async, Promise của main hoàn tất bình thường.