How to pass STDIN to a node.js child process

I use a library that wraps pandoc for node. But I can’t understand how to pass STDIN to the child process `execFile ...

 var execFile = require('child_process').execFile; var optipng = require('pandoc-bin').path; // STDIN SHOULD GO HERE! execFile(optipng, ['--from=markdown', '--to=html'], function (err, stdout, stderr) { console.log(err); console.log(stdout); console.log(stderr); }); 

In the CLI, it will look like this:

 echo "# Hello World" | pandoc -f markdown -t html 

UPDATE 1

Trying to make it work with spawn :

 var cp = require('child_process'); var optipng = require('pandoc-bin').path; var child = cp.spawn(optipng, ['--from=markdown', '--to=html'], { stdio: [ 0, 'pipe', 'pipe' ] }); child.stdin.write('# HELLO'); // then what? 
+6
source share
4 answers

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(); 
+5
source

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

As an alternative to using write() and listening to data , you can create a readable stream , push() your input, and then pipe() 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); 
+7
source

I'm not sure if you can use STDIN with child_process.execFile() based on these docs and the excerpt below, it looks like it is only available for 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 is generated directly as a new process, making it somewhat more efficient than child_process.exec ().

+1
source

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

 const child_process = require("child_process"); const str = "some string"; const result = child_process.spawnSync("somecommand", ["arg1", "arg2"], { input: str }); 
0
source

All Articles