将缓冲区传递给Node.jssubprocess

在我完成Node.jssubprocess的文档之后,我很好奇,是否可以将Buffer传递给这个进程。

https://nodejs.org/api/child_process.html

对我来说,似乎我只能通过string? 我怎样才能通过缓冲区或对象? 谢谢!

您只能传递缓冲区或string。

var node = require('child_process').spawn('node',['-i']); node.stdout.on('data',function(data) { console.log('child:: '+String(data)); }); var buf = new Buffer('console.log("Woof!") || "Osom\x05";\x0dprocess.exit();\x0d'); console.log('OUT:: ',buf.toString()) node.stdin.write(buf); 

输出:

 OUT:: console.log("Woof!") || "Osom♣"; process.exit(); child:: > child:: Woof! child:: 'Osom\u0005' child:: > 

因为.stdin是可写的stream 。

\x0d (CR)是交互模式下的“Enter”模拟。

你可以使用stream…

  var term=require('child_process').spawn('sh'); term.stdout.on('data',function(data) { console.log(data.toString()); }); var stream = require('stream'); var stringStream = new stream.Readable; var str="echo 'Foo Str' \n"; stringStream.push(str); stringStream.push(null); stringStream.pipe(term.stdin); var bufferStream= new stream.PassThrough; var buffer=new Buffer("echo 'Foo Buff' \n"); bufferStream.end(buffer); bufferStream.pipe(term.stdin);