Mr *_* Br 9 stream child-process node.js
我想使用自定义流来处理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]
});
Run Code Online (Sandbox Code Playgroud)
我收到错误Incorrect value for stdio stream.
有child_process.spawn https://nodejs.org/api/child_process.html#child_process_options_stdio的文档.它说stdio选项可以使用Stream对象
流对象 - 使用子进程共享引用tty,文件,套接字或管道的可读或可写流.
我想我错过了这个"指的"部分.
这似乎是一个错误:https://github.com/nodejs/node-v0.x-archive/issues/4030的customStream似乎当它传递到产卵是没有准备好().您可以轻松解决此问题:
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2973 次 |
| 最近记录: |