How to pass STDIN to node.js child process

前端 未结 4 1606
面向向阳花
面向向阳花 2020-12-07 01:10

I\'m using a library that wraps pandoc for node. But I can\'t figure out how to pass STDIN to the child process `execFile...

var execFile = requ         


        
4条回答
  •  不思量自难忘°
    2020-12-07 01:34

    Like spawn(), execFile() also returns a ChildProcess instance which has a stdin writable stream.

    As an alternative to using write() and listening for the data event, you could create a readable stream, push() your input data, and then pipe() it to child.stdin:

    var execFile = require('child_process').execFile;
    var stream   = require('stream');
    var optipng  = require('pandoc-bin').path;
    
    var child = execFile(optipng, ['--from=markdown', '--to=html'], function (err, stdout, stderr) {
        console.log(err);
        console.log(stdout);
        console.log(stderr);
    });
    
    var input = '# HELLO';
    
    var stdinStream = new stream.Readable();
    stdinStream.push(input);  // Add data to the internal queue for users of the stream to consume
    stdinStream.push(null);   // Signals the end of the stream (EOF)
    stdinStream.pipe(child.stdin);
    

提交回复
热议问题