How to pass STDIN to node.js child process

前端 未结 4 1589
面向向阳花
面向向阳花 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:29

    Here's how I got it to work:

    var cp = require('child_process');
    var optipng = require('pandoc-bin').path; //This is a path to a command
    var child = cp.spawn(optipng, ['--from=markdown', '--to=html']); //the array is the arguments
    
    child.stdin.write('# HELLO'); //my command takes a markdown string...
    
    child.stdout.on('data', function (data) {
        console.log('stdout: ' + data);
    });
    child.stdin.end();
    
    0 讨论(0)
  • 2020-12-07 01:30

    String as STDIN

    If you are using synchronous methods (execFileSync, execSync, or spawnSync) you can pass a string as stdin using the input key in options. Like this:

    const child_process = require("child_process");
    const str = "some string";
    const result = child_process.spawnSync("somecommand", ["arg1", "arg2"], { input: str });
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-12-07 01:35

    I'm not sure its possible to use STDIN with child_process.execFile() based on these docs and the below excerpt, looks like its available only to child_process.spawn()

    The child_process.execFile() function is similar to child_process.exec() except that it does not spawn a shell. Rather, the specified executable file is spawned directly as a new process making it slightly more efficient than child_process.exec().

    0 讨论(0)
提交回复
热议问题