【问题标题】:Pass a Buffer to a Node.js Child Process将缓冲区传递给 Node.js 子进程
【发布时间】:2015-06-19 12:06:19
【问题描述】:

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

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

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

【问题讨论】:

  • 子进程无法理解缓冲区或对象怎么办?
  • 你不能通过子流(stdin、ipc 等)发送它吗? nodejs 中的流可以接受字符串或缓冲区

标签: javascript node.js subprocess


【解决方案1】:

您只能传递 Buffer 或字符串。

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:: >

因为.stdinwritable stream

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

【讨论】:

  • 您将如何通过数据传递选项?例如,我可以发送两个参数 write(buf, options) 吗?谢谢
  • @JohnSmith 运行交互式node -i 或打开控制台(cmd)。您只能传递字符。仅有的。 Node.exe(和所有其他控制台应用程序)逐个字符地读取输入字符。而已。 stdinstdout 是一个字符流。阅读有关此内容。 ;) en.wikipedia.org/wiki/Standard_streams 所以。您可以将对象转换为字符串(JSON.stringify())并在孩子中解析它,如果他可以JSON.parse()
  • 感谢@befzz 提供此信息。但这是否意味着我不能传递 Filestream?
  • 也许你可以帮我解决这个问题:stackoverflow.com/questions/30943250/…
【解决方案2】:

你可以使用流...

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

【讨论】:

【解决方案3】:

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

输入 | | | 将作为标准输入传递给衍生进程的值。提供此值将覆盖 stdio[0]。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-15
    • 2014-08-15
    • 2022-08-14
    • 1970-01-01
    • 2010-10-11
    • 2016-02-06
    • 2017-11-10
    相关资源
    最近更新 更多