我需要在node.js函数

result = execSync('node -v');

它将同步执行给定的命令行并返回该命令文本的所有stdout。

ps.同步错误。我知道。仅供个人使用。

更新

现在我们有了mgutz的解决方案,它给出了退出代码,但没有stdout!还在等更确切的答案。

更新

Mgutz更新了他的答案,解决方案在这里:) 同样,作为dgo。一提到,有一个独立的模块execc -sync

更新2014-07-30

ShellJS lib到了。考虑到这是目前最好的选择。


更新2015-02-10

终于!NodeJS 0.12原生支持execSync。 查看官方文件


当前回答

在node.js中有一个很棒的流控制模块叫做asyncblock。如果在函数中包装代码对您的情况是OK的,那么可以考虑以下示例:

var asyncblock = require('asyncblock');
var exec = require('child_process').exec;

asyncblock(function (flow) {
    exec('node -v', flow.add());
    result = flow.wait();
    console.log(result);    // There'll be trailing \n in the output

    // Some other jobs
    console.log('More results like if it were sync...');
});

其他回答

在node.js中有一个很棒的流控制模块叫做asyncblock。如果在函数中包装代码对您的情况是OK的,那么可以考虑以下示例:

var asyncblock = require('asyncblock');
var exec = require('child_process').exec;

asyncblock(function (flow) {
    exec('node -v', flow.add());
    result = flow.wait();
    console.log(result);    // There'll be trailing \n in the output

    // Some other jobs
    console.log('More results like if it were sync...');
});

您可以使用纤维来实现这一点。例如,使用我的Common Node库,代码看起来是这样的:

result = require('subprocess').command('node -v');

我也遇到过类似的问题,最后我为此写了一个节点扩展。您可以查看git存储库。它是开源的,免费的,还有所有这些好东西!

https://github.com/aponxi/npm-execxi

ExecXI是一个用c++编写的用于执行shell命令的节点扩展 依次将命令的输出输出到控制台中 实时的。有可选的链式和非链式方式;意义 您可以选择在命令失败后停止脚本 (被锁住),或者你可以继续,就当什么都没发生!

使用说明在ReadMe文件中。请随意进行拉请求或提交问题!

编辑:但是它还没有返回标准输出…只是实时输出。现在有了。嗯,我今天刚刚发布。也许我们可以以此为基础。

不管怎样,我觉得值得一提。

使用ShellJS模块。

不提供回调函数的Exec函数。

例子:

var version = exec('node -v').output;

5年来,我的方法是有两条线;

const { execSync } = require('child_process');
const shell = (cmd) => execSync(cmd, {encoding: 'utf8'});

然后享受: Shell ('git remote -v') 或 Out = shell('ls -l') . .等等