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


当前回答

参见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'));

其他回答

我习惯于在回调函数的末尾实现“同步”的东西。不是很好,但是很有效。如果您需要实现一系列命令行执行,则需要将exec包装到某个命名函数中并递归调用它。 这个模式对我来说似乎很有用:

SeqOfExec(someParam);

function SeqOfExec(somepParam) {
    // some stuff
    // .....
    // .....

    var execStr = "yourExecString";
    child_proc.exec(execStr, function (error, stdout, stderr) {
        if (error != null) {
            if (stdout) {
                throw Error("Smth goes wrong" + error);
            } else {
                // consider that empty stdout causes
                // creation of error object
            }
        }
        // some stuff
        // .....
        // .....

        // you also need some flag which will signal that you 
        // need to end loop
        if (someFlag ) {
            // your synch stuff after all execs
            // here
            // .....
        } else {
            SeqOfExec(someAnotherParam);
        }
    });
};

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

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

参见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'));

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

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

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

我实际上遇到过这样的情况,我需要从一个包中一个接一个地运行多个命令。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/