Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass STDIN to node.js child process

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 = 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);
});

On the CLI it would look like this:

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

UPDATE 1

Trying to get it working 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?
like image 510
emersonthis Avatar asked Jun 07 '16 17:06

emersonthis


People also ask

What is child_process spawn?

The node:child_process module provides the ability to spawn subprocesses in a manner that is similar, but not identical, to popen(3) . This capability is primarily provided by the child_process. spawn() function: const { spawn } = require('node:child_process'); const ls = spawn('ls', ['-lh', '/usr']); ls. stdout.

What is Stdin Nodejs?

The stdin property of the process object is a Readable Stream. It uses on() function to listen for the event.

What is stdin and stdout in node JS?

stdin (0): The standard input stream, which is a source of input for the program. process. stdout (1): The standard output stream, which is a source of output from the program. process. stderr (2): The standard error stream, which is used for error messages and diagnostics issued by the program.


1 Answers

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);
like image 165
TachyonVortex Avatar answered Sep 16 '22 13:09

TachyonVortex