Reputation: 4167
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
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?
my node version:
> roroco@roroco ~/Dropbox/js/ro-evernote $ node -v
v7.3.0
Upvotes: 2
Views: 2408
Reputation: 3247
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). 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.
Keep in mind passing file descriptors is one of Node's only ways of IPC.
Upvotes: 3
Reputation: 4167
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"
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]});
})
Upvotes: 0