将子进程的输出保存在NodeJS的父级变量中 [英] Saving the output of a child process in a variable in the parent in NodeJS

查看:55
本文介绍了将子进程的输出保存在NodeJS的父级变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在NodeJS中启动一个子进程并将其输出保存到变量中.以下代码将其提供给stdout:

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

test 的值应该是 Hello World .

这不起作用,因为"test" 不是有效的stdio值.

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.

推荐答案

execSync 是一个返回所传递命令的标准输出的函数,因此您可以使用以下代码将其输出存储到变量中:

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"

请注意,如果进程的退出代码为非零,这将引发错误.另外,请注意,您可能需要使用 test.toString(),因为 child_process.execSync 可以返回 Buffer .

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.

这篇关于将子进程的输出保存在NodeJS的父级变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆