我需要在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。 查看官方文件


当前回答

只是补充一点,尽管你应该使用它们的用例很少,但在这些提交中,spawnSync / execFileSync / execSync被添加到node.js: https://github.com/joyent/node/compare/d58c206862dc...e8df2676748e

其他回答

在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...');
});

你可以在nodejs中执行同步shell操作,如下所示:

var execSync = function(cmd) {

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

    //for linux use ; instead of &&
    //execute your command followed by a simple echo 
    //to file to indicate process is finished
    exec(cmd + " > c:\\stdout.txt && echo done > c:\\sync.txt");

    while (true) {
        //consider a timeout option to prevent infinite loop
        //NOTE: this will max out your cpu too!
        try {
            var status = fs.readFileSync('c:\\sync.txt', 'utf8');

            if (status.trim() == "done") {
                var res = fs.readFileSync("c:\\stdout.txt", 'utf8');
                fs.unlinkSync("c:\\stdout.txt"); //cleanup temp files
                fs.unlinkSync("c:\\sync.txt");
                return res;
            }
        } catch(e) { } //readFileSync will fail until file exists
    }

};

//won't return anything, but will take 10 seconds to run
console.log(execSync("sleep 10")); 

//assuming there are a lot of files and subdirectories, 
//this too may take a while, use your own applicable file path
console.log(execSync("dir /s c:\\usr\\docs\\"));

编辑-本例适用于windows环境,如有必要可根据您自己的linux需求进行调整

我实际上遇到过这样的情况,我需要从一个包中一个接一个地运行多个命令。json preinstall脚本的一种方式,将工作在Windows和Linux/OSX,所以我不能依赖于非核心模块。

这就是我想到的:

#cmds.coffee
childproc = require 'child_process'

exports.exec = (cmds) ->
  next = ->
    if cmds.length > 0
      cmd = cmds.shift()
      console.log "Running command: #{cmd}"
      childproc.exec cmd, (err, stdout, stderr) ->
        if err? then console.log err
        if stdout? then console.log stdout
        if stderr? then console.log stderr
        next()
    else
      console.log "Done executing commands."

  console.log "Running the follows commands:"
  console.log cmds
  next()

你可以这样使用它:

require('./cmds').exec ['grunt coffee', 'nodeunit test/tls-config.js']

EDIT:正如所指出的,这实际上并不返回输出,也不允许您在Node程序中使用命令的结果。另一个想法是使用LiveScript回调。http://livescript.net/

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

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

这在Node.js中是不可能的,无论是child_process。Spawn和child_process。Exec是从底层构建为异步的。

详情见:https://github.com/ry/node/blob/master/lib/child_process.js

如果你真的想要这种阻塞,那么把所有需要发生的事情都放在回调中,或者构建自己的队列以阻塞的方式处理它,我想你可以使用Async.js来完成这个任务。

或者,如果你有太多的时间,可以在Node.js中自己动手。