2016-06-07 14 views
6

Ich verwende eine Bibliothek, die pandoc für Knoten umschließt. Aber ich kann nicht herausfinden, wie STDIN das Kind Prozess passieren `execfile ...Wie Übergeben von STDIN an den untergeordneten Prozess node.js

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

Auf dem CLI es würde wie folgt aussehen:

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

UPDATE 1

es die Arbeit mit spawn erhalten Versuch:

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? 

Antwort

3

Hier ist, wie ich es an die Arbeit:

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(); 
1

Ich bin nicht sicher, ob seine mögliche STDIN mit child_process.execFile() auf diesen docs und unter Auszug Basis zu verwenden, wie die verfügbaren sieht nur 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

Können Sie zeigen, wie die STDIN mit passieren laichen? – emersonthis

+0

@emersonthis folgen Sie den Dokument-Link, den ich in der Antwort geschrieben habe, und es zeigt, wie man in einem Code-Snippet. – peteb

+0

Ich war tatsächlich auf dieser Seite für die letzte Stunde und ich kann es nicht zur Arbeit bringen ... – emersonthis

6

Wie spawn(), gibt execFile() auch eine ChildProcess Instanz zurück, die einen beschreibbaren stdin Stream hat.

Als Alternative zu write() mit und für das data Ereignis hören, könnten Sie ein readable stream, push() Ihre Eingangsdaten erstellen und dann pipe() es 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); 
Verwandte Themen