2018-02-19 A console.log gotcha in Node.js

I’ve been writing a certain Node.js script recently, and I was caught by surprise with an innocent-looking console.log. So, here is my warning to all unsuspecting Node.js script writers.

Since the script is under development, I do not bother with outputting the results to a file with fs.writeFileSync, but just console.log them to stdout. (And at some point, the output was a huge object, written out with JSON.stringify.) So far, so good.

For certain reasons (mainly my sloppiness) I ended the script with a process.exit(0). This is probably bad practice, and I switched to properly closing my database connections afterward –this is what you should do anyway. (If you don’t close your connections, or leave some other non-blocking operation turned on, your script will seem to hang and you’ll have to Ctrl-C out of it.) So far, so good – this is WiP, so a process.exit(0) won’t do any harm, right?

Well, wrong. It turns out that console.log (and its ilk) is sometimes non-blocking! I didn’t expect that. And it wouldn’t be that bad if not for the fact that the synchronicity of writes to stdout (and stderr, for that matter) depend on two things: whether the output is linked to a terminal or e.g. to a pipe, and whether you are on Windows or on a POSIX operating system. This doesn’t make sense at all to me, but it is what it is. Be warned.

CategoryEnglish, CategoryBlog, CategoryJavaScript