Search code examples
javascriptnode.jssubprocess

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!


Solution

  • 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.