Put output of evaluated file into another file in Nodejs

In my Nodejs script I have a line, called on demand:

eval(fs.readFileSync('eval.js')+'');

It is done so, because sometimes I want to know about what is going on in my "nodejs script", the content of it's variables.

So, "eval.js" usually represented as:

console.dir(myVar);

The problem is, it outputs in console output. "Parent" script also outputs in console some info, so the console is running very fast and I can't get that I want.

I was searching any way to put all output of file "eval.js" into another file "x.log".

Something like (in "parent" script):

evalFileToLog("eval.js", "x.log");

Or "eval.js":

// something what will forward stdout to "x.log"
console.dir(abc);
// blah blah blah
// something that will restore stdout to it's normal behaviour, like it was before.

Thank you for your help!

You can write to another stream (eg a file or standard error) to separate your outputs, but I highly advise against doing synchronous reads of any file in your program.

Another way to get a view into your app would be to leverage the repl with it you can have a shell in your program instead of flooding the output.

var repl = require('repl');
var bar = new MyApp();
relp.start({
  foo: bar
});

And now you have bar exposed in your shell.