【问题标题】:Nodejs child_process spawn custom stdioNodejs child_process 生成自定义 stdio
【发布时间】:2016-04-30 06:25:26
【问题描述】:

我想使用自定义流来处理 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]
});

我收到错误Incorrect value for stdio stream

有 child_process.spawn https://nodejs.org/api/child_process.html#child_process_options_stdio 的文档。它表示 stdio 选项可以采用 Stream 对象

流对象 - 与子进程共享指向 tty、文件、套接字或管道的可读或可写流。

我想我错过了这个“引用”部分。

【问题讨论】:

    标签: node.js stream child-process


    【解决方案1】:

    这似乎是一个错误: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);
    

    【讨论】:

    • 是的,这是我最后使用的东西。谢谢
    • 虽然这是一个很好的解决方法,但实际问题是 stdio 流需要底层文件描述符。自定义流没有。
    猜你喜欢
    • 1970-01-01
    • 2021-12-31
    • 2023-02-07
    • 2014-07-05
    • 2020-12-12
    • 1970-01-01
    • 2014-02-03
    • 1970-01-01
    • 2021-02-22
    相关资源
    最近更新 更多