Node.js:如果方法抛出异常,则不会显示 console.log 消息......为什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19733472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js: console.log message doesn't show up if method throws exception... why?
提问by Shaun
In Node.js, if I have a method that throws an exception, console.log statements from that method don't fire. I recognize that in the simple test case below that I should catch the exception from the readFileSync call, or otherwise be defensive about it. Just curious if someone could explain the behavior to me.
在 Node.js 中,如果我有一个抛出异常的方法,那么来自该方法的 console.log 语句不会触发。我认识到在下面的简单测试用例中,我应该从 readFileSync 调用中捕获异常,或者对其进行防御。只是好奇是否有人可以向我解释这种行为。
Simple test case:
简单的测试用例:
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");
Output:
输出:
$ 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)
回答by Shaun
Ah, figured it out.
啊,想通了。
It seems that console.log isn't finishing before the process exits... If I use console.warn, the message does show up.
似乎 console.log 在进程退出之前没有完成......如果我使用 console.warn,消息确实会显示出来。
This post explains it: is node.js' console.log asynchronous?
这篇文章解释了它:node.js 的 console.log 是异步的吗?
Also, I'm on an older version (0.8.15), so this may no longer be relevant.
另外,我使用的是旧版本(0.8.15),所以这可能不再相关。

