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"
}
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"
}
これは、私が現在取り組んでいるプロジェクトで使用している方法です。
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", "") });
});
});
};
あなたは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 のようなものには近づかないでください。か何か。
レナートの回答のおかげで、私は本当に基本的な例を作成しました:
const exec = require('child_process').exec
exec('git config --global user.name', (err, stdout, stderr) => console.log(stdout))
グローバルgitユーザー名を出力するだけです:)