What is the output of the following Node.js code?
4 phương ánCó giải thích
const fs = require('fs');
function readTwoFiles(file1, file2, callback) {
fs.readFile(file1, 'utf8', (err, data1) => {
if (err) return callback(err);
fs.readFile(file2, 'utf8', (err, data2) => {
if (err) return callback(err);
callback(null, data1 + data2);
});
});
}
readTwoFiles('file1.txt', 'file2.txt', (err, result) => {
if (err) {
console.log('Error:', err.message);
} else {
console.log('Result:', result);
}
});Assume 'file1.txt' contains "Hello" and 'file2.txt' 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 'file2.txt'". Lần theo mã: readTwoFiles gọi fs.readFile cho file1.txt, tệp tồn tại nên err là null và data1 bằng Hello; trong callback đó nó gọi tiếp fs.readFile cho file2.txt, tệp không tồn tại nên Node trả lỗi có code ENOENT với thông điệp no such file or directory, open 'file2.txt'; nhánh if (err) return callback(err) chuyển lỗi ra ngoài và callback cuối chạy console.log('Error:', err.message), in chữ Error: rồi một dấu cách và thông điệp lỗi. "Result: Hello" sai vì callback(null, data1 + data2) chỉ chạy khi cả hai lần đọc đều thành công. "Error: ENOENT: no such file or directory, open 'file1.txt'" sai vì file1.txt đọc được, lỗi phát sinh ở tệp thứ hai. "Result: undefined" sai vì khi có lỗi mã thoát sớm bằng return, nhánh in Result không bao giờ chạy.