Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving the output of a child process in a variable in the parent in NodeJS

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.

like image 955
pfo Avatar asked Dec 06 '16 17:12

pfo


People also ask

What is child_process spawn?

child_process. exec() : spawns a shell and runs a command within that shell, passing the stdout and stderr to a callback function when complete. child_process. execFile() : similar to child_process. exec() except that it spawns the command directly without first spawning a shell by default.

What is fork in node js with example?

fork method is a special case of the spawn() to create Node processes. This method returns object with a built-in communication channel in addition to having all the methods in a normal ChildProcess instance. Syntax: child_process. fork(modulePath[, args][, options])


1 Answers

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.

like image 152
Aurora0001 Avatar answered Sep 16 '22 19:09

Aurora0001