node.jsでシェルコマンドを実行して出力を取得する 質問する

node.jsでシェルコマンドを実行して出力を取得する 質問する

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"
}

ベストアンサー1

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

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", "") });
        });
    });
};

おすすめ記事