Search code examples
node.jsbufferchild-processspawnjsonparser

child_process.spawn returning buffer object


const cp = require("child_process");

ls = cp.spawn("node", ["./scripts/test.js"]);

ls.stdout.on("data", (data) => {
    console.log(`stdout": ${data}`);

    const result = data.toString();

  });

In ls.stdout.on i am getting data as buffer and if i do it to data.toString() it gives me result like "{evenNumberSum :8, oddNumberSum:6}" but i want result as a JSON object i am not even able to parse this type of result can anyone give me a better way to get result from buffer

CurrentOutput:
<Buffer 7b 3a 6e 61 6d 65 3d 3e 22 4a 6f 68 6e 22 2c 20 3a 61 67 65 3d 3e 33 30 2c 20 3a 63 69 74 79 3d 3e 22 4e 65 77 20 59 6f 72 6b 22 7d 0a>


Required Output:
{evenNumberSum :8, oddNumberSum:6}

test.js

let result = {};
function add(val1, val2) {
  return val1 + val2;
}
result.evenNumbersSum = add(2, 4);
result.oddNumbersSum = add(1, 3);
result.mixNumbersSum = add(1, 2);
console.log(result);

Solution

  • I am not sure what test.js looks like, but I was not able to reproduce this issue.

    I am using the following code..


    --EDIT/DISCLAIMER-- People are most likely downvoting this because the solution I provided uses eval. To summarize:

    • YOU SHOULD USE eval AS LITTLE AS POSSIBLE (in a perfect world, eval would never be used)
    • ONLY USE IT ON *TRUSTED* strings (aka DO NOT USE eval ON USER SUPPLIED DATA!!! EVER.)

    Considering the disclaimer above, the only way I could get this to work was:

    main.js:

    const cp = require('child_process');
    
    ls = cp.spawn('node', ['./test.js']);
    
    ls.stdout.on('data', (data) => {
      const dataString = data.toString();
      const dataJson = eval(`(${dataString})`);
    
      console.log('Data as JSON  =', dataJson);
      console.log('evenNumberSum =', dataJson.evenNumberSum);
      console.log('oddNumberSum  =', dataJson.oddNumberSum);
    });
    

    test.js:

    console.log({ evenNumberSum: 8, oddNumberSum: 6 }); 
    

    Which produces the following output:

    Data as JSON  = { evenNumberSum: 8, oddNumberSum: 6 }
    evenNumberSum = 8
    oddNumberSum  = 6