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

Joh*_*ith 6 javascript subprocess node.js

在浏览完 Node.js 子进程的文档后,我很好奇是否可以将 Buffer 传递给该进程。

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

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

bef*_*fzz 4

您只能传递 Buffer 或字符串。

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

输出:

\n\n
OUT::  console.log("Woof!") || "Osom\xe2\x99\xa3";\nprocess.exit();\nchild:: >\nchild:: Woof!\n\nchild:: \'Osom\\u0005\'\n\nchild:: >\n
Run Code Online (Sandbox Code Playgroud)\n\n

因为.stdin可写流

\n\n

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

\n