在Node.js中,如果我有一个抛出异常的方法,那么该方法的console.log语句不会触发。我认识到在下面的简单测试用例中,我应该从readFileSync调用中捕获异常,否则就会对它采取防御措施。只是好奇是否有人可以向我解释这种行为。
简单的测试用例:
var fs = require('fs');
function readAFileThatDoesntExist(filename) {
console.log(filename);
fs.readFileSync(filename);
}
console.log("We're about to read a file that doesn't exist!");
readAFileThatDoesntExist("afile");
输出:
$ node test.js
We're about to read a file that doesn't exist!
fs.js:338
return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
^
Error: ENOENT, no such file or directory 'C:\blog\projects\bloggen\scripts\afile'
at Object.fs.openSync (fs.js:338:18)
at Object.fs.readFileSync (fs.js:182:15)
at readAFileThatDoesntExist (C:\blog\projects\bloggen\scripts\test.js:5:8)
at Object.<anonymous> (C:\blog\projects\bloggen\scripts\test.js:9:1)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
答案 0 :(得分:21)
似乎console.log在进程退出之前没有完成...如果我使用console.warn,则消息确实显示出来。
这篇文章解释了它:is node.js' console.log asynchronous?
另外,我的版本较旧(0.8.15),因此可能不再适用。