将缓冲区传递给节点.js子进程
Pass a Buffer to a Node.js Child Process
在我浏览了 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);
相关文章:
- 节点Js:How to catch a“;没有这样的文件或目录“;读取线模块出错
- 节点.js将变量显示为 HTML
- 如何解决'窗口未定义'终端上的节点JS出错
- S3文件上传文件对象使用节点js
- 在节点 js 中使用护照本地模块验证(登录)密码时出错
- 嵌套的promise节点js
- 使用节点JS发送电子邮件
- 节点JS重定向循环
- 起始节点.js用于并行的线程池
- 获取图像节点js的主色
- 调整节点js中的图像大小
- 节点JS express和控制台输出到命令行与浏览器
- 节点JS:时间机器坏了——timekeeper.travel不做时间旅行
- 如何访问日期并将其插入数据库?节点.JS&MongoDB
- 节点.js快速删除 req.body 不起作用
- 节点.js中的嵌套异步操作
- 如何在核心php应用程序中使用节点js json Web令牌库
- 使用节点js的Bootstrap和Jquery
- 节点.js加密输入/输出类型
- 节点.js在不可能的地方打印“未定义”