我查看了 Node.js 子进程的文档,想知道是否可以将缓冲区传递给该进程。
https://nodejs.org/api/child_process.html
对我来说似乎只能传递字符串?如何传递缓冲区或对象?谢谢!
我查看了 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
是一个可写流 (writable stream)。
\x0d
(CR) 在交互模式下是“Enter”键的模拟。
write(buf,options)
的东西?谢谢。 - John Smithnode -i
或者打开控制台(cmd)。你只能传递字符。仅限字符。Node.exe (以及所有其他控制台应用程序) 逐个字符读取输入。没有更多了。stdin
和 stdout
是一个字符流。阅读一下这方面的内容吧。;) https://en.wikipedia.org/wiki/Standard_streams 所以,如果子进程可以使用 JSON.parse()
,你可以将对象转换为字符串(JSON.stringify()
)并在子进程中解析它。 - befzzYou 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);
git diff | git apply --reverse
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
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);