10

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.

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)
3
  • It works as expected for me (Node 0.10.10) Commented Nov 1, 2013 at 18:58
  • Works for me as well (v0.10.21). Commented Nov 1, 2013 at 19:00
  • Yeah, didn't realize how far back my node was... thanks. Commented Nov 1, 2013 at 19:01

1 Answer 1

26

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.

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

Also, I'm on an older version (0.8.15), so this may no longer be relevant.

Sign up to request clarification or add additional context in comments.

2 Comments

Many many thanks on sharing the alternative option of console.warn when working with node.js
Somehow this is relevant on node v18.12.1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.