Duncan Marshall
Duncan Marshall

Reputation: 550

Piping nodejs output to file doesn't capture execution halting error

I have a nodejs script which I'm running from the terminal like so:

node myscript.js

myscript.js contains this:

for (var i = 0;i < 3;i++){console.log(i);}

throw "Some error";

It output this:

0
1
2

/path/myscript.js:3
throw "Some error"
^
Some error

When I instead run it like this:

node myscript.js >> logfile.txt

And cat logfile.txt, I only get this output:

0
1
2

This is happening on an Alpine Docker container, but I've tried it on raspbian, and Linux Mint with the same result.

How can I get the error message (the thing I most want logged) to be stored in my logfile?

Upvotes: 0

Views: 31

Answers (1)

fragmentedreality
fragmentedreality

Reputation: 1317

You are only redirecting stdout to the file. If you also want to have the errors stderr in the file, you need to redirect that also.

node myscript.js 2>&1 >> logfile.txt

You could also capture errors in a separate file:

node myscript.js >> logfile.txt 2>> errors.txt

Upvotes: 1

Related Questions