简体   繁体   English

在nodejs中,生成直接stdout和stderr到日志文件不起作用

[英]in nodejs, spawn direct stdout and stderr to log file doesn't work

here is my code: 这是我的代码:

var spawn = require("child_process").spawn
var fs = require("fs")
var p = spawn("ls", ["prprpr"])
var log = fs.createWriteStream("/tmp/prpr.log")
p.stdout.pipe(log)
p.stderr.pipe(log)

when i cat /tmp/prpr.log , it return empty, but when i redirect to process.stdout and process.stderr, it output error correctly 当我使用cat /tmp/prpr.log ,它返回空,但是当我重定向到process.stdout和process.stderr时,它会正确输出错误

var spawn = require("child_process").spawn
var fs = require("fs")
var p = spawn("ls", ["prprpr"])
var log = fs.createWriteStream("/tmp/prpr.log")
p.stdout.pipe(process.stdout)
p.stderr.pipe(process.stderr)

how to make spawn stdout and stderr to disk file? 如何使生成标准输出和stderr到磁盘文件?

my node version: 我的节点版本:

> roroco@roroco ~/Dropbox/js/ro-evernote $ node -v
v7.3.0

I find the solution: 我找到了解决方案:

when i use following another way to redirect stdout: 当我使用以下另一种方式重定向标准输出时:

var fs = require("fs")
let log = fs.createWriteStream("/tmp/prpr.log");
const child = require("child_process").spawn('ls', ["prprpr"], {stdio: [null, log, log]});

it will raise 它会上升

TypeError: Incorrect value for stdio stream: WriteStream {

it's the reason why I cannot write to log 这就是为什么我无法写日志的原因

I find the solution in this answer , WriteStream can writable when "open" 我在这个答案中找到解决方案,“打开”时WriteStream可以写

and use following code will work: 并使用以下代码将起作用:

var fs = require("fs")
let log = fs.createWriteStream("/tmp/prpr.log");
log.on("open", function () {
  const child = require("child_process").spawn('ls', ["prprpr"], {stdio: [null, log, log]});
})

Virtually straight from the docs: 几乎直接来自文档:

const child_process = require("child_process");
const fs = require("fs");
const out = fs.openSync("./stdout.log", "a");
const err = fs.openSync("./stderr.log", "a");
const child = child_process.spawn("ls", ["-alc"], {
  stdio: [process.stdin, out, err]
});

You just need to pass the file descriptors to the stdio (no need to create streams). 您只需要将文件描述符传递给stdio(无需创建流)。 There are a lot of flavors for this here - specifically take note of how detached and passing 'ignore' for stdin impact how the child survives the parent process. 有很多味道此的在这里 -特别注意的是如何detached和通过'ignore'为标准输入影响孩子如何生存的父进程。

Keep in mind passing file descriptors is one of Node's only ways of IPC. 请记住,传递文件描述符是Node IPC唯一的方法之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM