将stdout重定向到文件node.js [英] Redirecting stdout to file nodejs

查看:351
本文介绍了将stdout重定向到文件node.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了:

var access = fs.createWriteStream('/var/log/node/api.access.log', { flags: 'w' });

然后通过管道传输:

process.stdout.pipe(access);

然后尝试:

console.log("test");

/var/log/node/api.access.log中没有任何内容.但是这种方式有效:

And nothing has appeared in /var/log/node/api.access.log. However this way is working:

process.stdout.pipe(access).write('test');

有人可以解释我在做什么错吗?

Could someone explain what am I doing wrong ?

推荐答案

我通过以下方式解决了这个问题:

I solved this problem the following way:

var access = fs.createWriteStream('/var/log/node/api.access.log');
process.stdout.write = process.stderr.write = access.write.bind(access);

当然,如果需要,您也可以将stdout和stderr分开.

Of course you can also separate stdout and stderr if you want.

我也强烈建议处理未捕获的异常:

I also would strongly recommend to handle uncaught exceptions:

process.on('uncaughtException', function(err) {
  console.error((err && err.stack) ? err.stack : err);
});

这将涵盖以下情况:

  • process.stdout.write
  • process.stderr.write
  • console.log
  • console.dir
  • console.error
  • someStream.pipe(process.stdout);
  • 抛出新的错误(崩溃");
  • 抛出从不这样做";
  • 未定义;

这篇关于将stdout重定向到文件node.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆