2016-06-07 65 views
6

Używam biblioteki, która opakowuje pandoc dla węzła. Ale nie mogę dowiedzieć się, jak przekazać STDIN do procesu potomnego `execfile ...Jak przekazać STDIN do procesu potomnego 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); 
}); 

Na CLI będzie wyglądać następująco:

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

UPDATE 1

próbując go pracy z 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? 

Odpowiedz

3

Oto jak mam go do pracy:

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

Nie jestem pewien jego możliwe wykorzystanie STDIN z child_process.execFile() w oparciu o te docs a poniżej fragment, wygląda jego dostępne tylko dla 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

można pokazać w jaki sposób przekazać STDIN korzystania ikra? – emersonthis

+0

@emersonthis postępuj zgodnie z linkiem do dokumentu, który zamieściłem w odpowiedzi i pokazuje, jak w kodzie źródłowym. – peteb

+0

Byłem na tej stronie przez ostatnią godzinę i nie mogę go uruchomić ... – emersonthis

6

Podobnie jak spawn(), execFile() zwraca również instancję ChildProcess, która ma zapisywalny strumień stdin.

Jako alternatywa do stosowania write() i słuchania dla zdarzenia data, można utworzyć readable stream, push() dane wejściowe, a następnie pipe() go 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); 
Powiązane problemy