155

node.js で、Unix ターミナル コマンドの出力を取得する方法を見つけたいと思います。これを行う方法はありますか?

function getCommandOutput(commandString){
    // now how can I implement this function?
    // getCommandOutput("ls") should print the terminal output of the shell command "ls"
}
4

7 に答える 7

179

これは、私が現在取り組んでいるプロジェクトで使用している方法です。

var exec = require('child_process').exec;
function execute(command, callback){
    exec(command, function(error, stdout, stderr){ callback(stdout); });
};

gitユーザーを取得する例:

module.exports.getGitUser = function(callback){
    execute("git config --global user.name", function(name){
        execute("git config --global user.email", function(email){
            callback({ name: name.replace("\n", ""), email: email.replace("\n", "") });
        });
    });
};
于 2012-10-17T18:47:32.707 に答える
37

あなたはchild_processを探しています

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

child = exec(command,
   function (error, stdout, stderr) {
      console.log('stdout: ' + stdout);
      console.log('stderr: ' + stderr);
      if (error !== null) {
          console.log('exec error: ' + error);
      }
   });

Renato が指摘したように、いくつかの同期 exec パッケージも現在出回っています。ただし、node.js はシングル スレッドの高性能ネットワーク サーバーとして設計されているため、それを使用する場合は、起動時にのみ使用する場合を除き、sync-exec のようなものには近づかないでください。か何か。

于 2012-10-17T18:44:51.757 に答える
21

レナートの回答のおかげで、私は本当に基本的な例を作成しました:

const exec = require('child_process').exec

exec('git config --global user.name', (err, stdout, stderr) => console.log(stdout))

グローバルgitユーザー名を出力するだけです:)

于 2018-07-17T13:15:42.063 に答える