Node.js: The console.log message is not displayed if the method throws an exception ... why?

In Node.js, if I have a method that throws an exception, the console.log statements from this method do not work. I admit that in the simple test case below, I have to catch an exception to the readFileSync call or otherwise defend myself. Just curious if anyone can explain my behavior.

A 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) 
+6
source share
1 answer

Ah, I realized that.

It seems that console.log does not end until the process exits ... If I use console.warn, a message appears.

This post explains: is node.js' console.log asynchronous?

In addition, I am in an earlier version (0.8.15), so this may not be relevant anymore.

+18
source

Source: https://habr.com/ru/post/957212/


All Articles