我需要在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中是不可能的,无论是child_process。Spawn和child_process。Exec是从底层构建为异步的。

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

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

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

这是我发现的最简单的方法:

exec-Sync: https://github.com/jeremyfa/node-exec-sync (不要与execSync混淆。) 同步执行shell命令。在迁移脚本、cli程序中使用这个选项,但不能用于常规的服务器代码。 例子:

var execSync = require('exec-sync');   
var user = execSync('echo $USER');
console.log(user);

Node.js(从0.12版本开始-有一段时间)支持execSync:

child_process.execSync(command[, options])

你现在可以直接这样做:

const execSync = require('child_process').execSync;
code = execSync('node -v');

它会如你所愿。(默认为将i/o结果管道到父进程)。注意,你现在也可以生成同步。

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

参见execSync库。

用node-ffi很容易做到。我不推荐服务器进程,但对于一般的开发实用程序,它可以完成任务。安装库。

npm install node-ffi

示例脚本:

var FFI = require("node-ffi");
var libc = new FFI.Library(null, {
  "system": ["int32", ["string"]]
});

var run = libc.system;
run("echo $USER");

[编辑2012年6月:如何获得STDOUT]

var lib = ffi.Library(null, {
    // FILE* popen(char* cmd, char* mode);
    popen: ['pointer', ['string', 'string']],

    // void pclose(FILE* fp);
    pclose: ['void', [ 'pointer']],

    // char* fgets(char* buff, int buff, in)
    fgets: ['string', ['string', 'int','pointer']]
});

function execSync(cmd) {
  var
    buffer = new Buffer(1024),
    result = "",
    fp = lib.popen(cmd, 'r');

  if (!fp) throw new Error('execSync error: '+cmd);

  while(lib.fgets(buffer, 1024, fp)) {
    result += buffer.readCString();
  };
  lib.pclose(fp);

  return result;
}

console.log(execSync('echo $HOME'));