John Smith
John Smith

Reputation: 6259

Pass a Buffer to a Node.js Child Process

After I went through the documentation for Node.js Child Processes, I was curious If it would be possible to pass a Buffer to this Process.

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

For me it seems like I only can pass Strings? How can I pass Buffers or Objects? Thanks!

Upvotes: 6

Views: 8485

Answers (4)

Ben Barnes
Ben Barnes

Reputation: 156

If you use child_process.fork() you can send Buffer from parent to child in such way:

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

and parse it

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

Upvotes: 0

Mr. Doge
Mr. Doge

Reputation: 886

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 <string> | <Buffer> | <TypedArray> | <DataView> The value which will be passed as stdin to the spawned process. Supplying this value will override stdio[0].

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

Upvotes: 0

befzz
befzz

Reputation: 1292

You can pass only Buffer or string.

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

Output:

OUT::  console.log("Woof!") || "Osom♣";
process.exit();
child:: >
child:: Woof!

child:: 'Osom\u0005'

child:: >

Because .stdin is writable stream.

\x0d(CR) is an 'Enter' simulation in interactive mode.

Upvotes: 4

cswl
cswl

Reputation: 453

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

Upvotes: 2

Related Questions