我想使用自定义流来处理 child_process.spawn stdio。
例如
const cp = require('child_process');
const process = require('process');
const stream = require('stream');
var customStream = new stream.Stream();
customStream.on('data', function (chunk) {
console.log(chunk);
});
cp.spawn('ls', [], {
stdio: [null, customStream, process.stderr]
});
我收到错误 stdio 流的值不正确
。
有 child_process.spawn https://nodejs.org/api/child_process.html#child_process_options_stdio 的文档.它表示 stdio 选项可以采用 Stream 对象
Stream object - Share a readable or writable stream that refers to a tty, file, socket, or a pipe with the child process.
我想我错过了这个“引用”部分。
最佳答案
这似乎是一个错误:https://github.com/nodejs/node-v0.x-archive/issues/4030 customStream
在传递给 spawn() 时似乎还没有准备好。您可以轻松解决此问题:
const cp = require('child_process');
const stream = require('stream');
// use a Writable stream
var customStream = new stream.Writable();
customStream._write = function (data) {
console.log(data.toString());
};
// 'pipe' option will keep the original cp.stdout
// 'inherit' will use the parent process stdio
var child = cp.spawn('ls', [], {
stdio: [null, 'pipe', 'inherit']
});
// pipe to your stream
child.stdout.pipe(customStream);
关于node.js - Nodejs child_process 生成自定义 stdio,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34967278/