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

Pass a Buffer to a Node.js Child Process

本文关键字:节点 js 子进程 缓冲区      更新时间:2023-09-26

在我浏览了 Node.js 子进程的文档后,我很好奇是否可以将缓冲区传递给此进程。

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

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

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

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是可写流。

'x0d (CR) 是交互模式下的"输入"模拟。

您可以使用流...

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

git diff | git apply --reverse

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
input | | <<p>TypedArray> | 将作为 stdin 传递给生成进程的值。提供此值将覆盖 stdio[0]。

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

如果你使用child_process.fork()你可以通过以下方式将缓冲区从父级发送到子级:

const message = JSON.stringify(buffer);
child.send(message);

并解析它

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