1

I'm running a node application as a daemon. When debugging the daemon, I need to see the output, so I'd like to redirect stdout and stderr to a file.

I'd expect I can just reassign stdout and stderr like in Python or C:

fs = require('fs');
process.stdout = fs.openSync('/var/log/foo', 'w');
process.stderr = process.stdout;
console.log('hello');

When I run the script directly, "hello" is printed to the console! Of course when I run in the background, I see output neither on the console (of course) or in /var/log/foo.

I don't want or need sophisticated logging. I just need to see the builtin messages that node already provides.

3
  • 1
    The whole point of Node.js is to use another module. Commented Sep 18, 2013 at 21:03
  • The other module hooks into node somehow. I want to know how, so I can do it myself. Commented Sep 18, 2013 at 21:04
  • Read its source code. Commented Sep 22, 2013 at 1:48

2 Answers 2

1

The console object grabs a reference to process.stdout and stderr when it is first created.
(you can see this in the source).

Re-assigning them later does not affect console.

The usual way to redirect these streams is to launch the process with the streams redirected.

Alternatively, you can overwrite the console methods and make them write to your file instead.

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

Comments

0

Similar to this question, you can overwrite process.stdout.write which is called from console.log.

var fs = require('fs');
var oldWrite = process.stdout.write;

process.stdout.write = function (d) {
    fs.appendFileSync('./foo', d);
    oldWrite.apply(this, arguments);
};

console.log('hello');

Comments

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.