将缓冲区传递给Node.js子进程

6

我查看了 Node.js 子进程的文档,想知道是否可以将缓冲区传递给该进程。

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

对我来说似乎只能传递字符串?如何传递缓冲区或对象?谢谢!


如果子进程无法理解缓冲区或对象,会怎么样? - thefourtheye
2
你不能通过子流(stdin、ipc等)发送它吗?在Node.js中,流可以接受字符串或缓冲区。 - slebetman
4个回答

4

您只能传递缓冲区或字符串。

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 是一个可写流 (writable stream)。

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


你如何将选项与数据一起传递?例如,是否有类似于我可以发送两个参数write(buf,options)的东西?谢谢。 - John Smith
@JohnSmith 运行交互式的 node -i 或者打开控制台(cmd)。你只能传递字符。仅限字符。Node.exe (以及所有其他控制台应用程序) 逐个字符读取输入。没有更多了。stdinstdout 是一个字符流。阅读一下这方面的内容吧。;) https://en.wikipedia.org/wiki/Standard_streams 所以,如果子进程可以使用 JSON.parse(),你可以将对象转换为字符串(JSON.stringify())并在子进程中解析它。 - befzz
感谢 @befzz 提供这个信息。但是这是否意味着我不能传递一个文件流? - John Smith
也许你可以帮我回答这个问题:http://stackoverflow.com/questions/30943250/pass-buffer-to-childprocess-node-js - John Smith

2

You can use streams...

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

也许你可以帮我回答这个问题:http://stackoverflow.com/questions/30943250/pass-buffer-to-childprocess-node-js - John Smith

0

git diff | git apply --reverse

git diff | git apply --reverse

是一个与Git版本控制系统相关的命令。它用于撤销先前应用的补丁,使代码回到之前的状态。如果您在编写代码时犯了错误或需要回滚更改,这个命令将非常有用。

const { execSync } = require('child_process')

const patch = execSync(`git diff -- "${fileName}"`, { cwd: __dirname }
//patch is a Buffer
execSync(`git apply --reverse`, { cwd: __dirname, input: thePatch })

echo Hello, World! | cat

const { execSync } = require('child_process')

const output = execSync(`cat`, { cwd: __dirname, input: "Hello, World!" })
console.log(output) //Buffer
console.log(output.toString()) //string

输入 <字符串> | <缓冲区> | <类型化数组> | <数据视图> 将传递给生成的进程的标准输入值。提供此值将覆盖 stdio[0]。

https://nodejs.org/api/child_process.html#child_processexecsynccommand-options


0
如果您使用child_process.fork(),您可以以这种方式将缓冲区从父进程发送到子进程:
const message = JSON.stringify(buffer);
child.send(message);

并解析它

const buffer = Buffer.from(JSON.parse(message).data);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接