Saving the output of a child process in a variable in the parent in NodeJS
Asked Answered
F

1

14

I would like to start a child process in NodeJS and save it's output into a variable. The following code gives it to stdout:

require("child_process").execSync("echo Hello World", {"stdio": "inherit"});

I have something in mind that is similar to this code:

var test;
require("child_process").execSync("echo Hello World", {"stdio": "test"});
console.log(test);

The value of test was supposed to be Hello World.

Which does not work, since "test" is not a valid stdio value.

Perhaps this is possible using environment variables, however I did not find out how to modify them in the child process with the result still being visible to the parent.

Fruma answered 6/12, 2016 at 17:29 Comment(0)
A
22

execSync is a function which returns the stdout of the command you pass in, so you can store its output into a variable with the following code:

var child_process = require("child_process");
var test = child_process.execSync("echo Hello World");
console.log(test);
// => "Hello World"

Be aware that this will throw an error if the exit code of the process is non-zero. Also, note that you may need to use test.toString() as child_process.execSync can return a Buffer.

Aframe answered 6/12, 2016 at 17:41 Comment(3)
Thank you for your answer! I would like to add that I had to use test.toString(), otherwise the output was <Buffer 48 65 6c 6c 6f 20 57 6f 72 6c 64 0a>.Fruma
@Fruma will note this - I think it varies with the version since my local copy didn't do that.Aframe
How do you do that if it exists with a non-zero exit code though?Bottomless

© 2022 - 2024 — McMap. All rights reserved.