Hala bir linux veya windows shell komutunu nasıl çalıştırabileceğime ve node.js içinde çıktıyı nasıl yakalayabileceğime dair daha ince noktaları kavramaya çalışıyorum; sonuçta böyle bir şey yapmak istiyorum ...
//pseudocode
output = run_command(cmd, args)
Önemli outputolan, küresel kapsamlı bir değişken (veya nesne) için mevcut olması gerektiğidir. Aşağıdaki işlevi denedim, ancak nedense undefinedkonsola yazdırıldım ...
function run_cmd(cmd, args, cb) {
var spawn = require('child_process').spawn
var child = spawn(cmd, args);
var me = this;
child.stdout.on('data', function(me, data) {
cb(me, data);
});
}
foo = new run_cmd('dir', ['/B'], function (me, data){me.stdout=data;});
console.log(foo.stdout); // yields "undefined" <------
Yukarıdaki kodun nerede kırıldığını anlamakta güçlük çekiyorum ... bu modelin çok basit bir prototipi çalışıyor ...
function try_this(cmd, cb) {
var me = this;
cb(me, cmd)
}
bar = new try_this('guacamole', function (me, cmd){me.output=cmd;})
console.log(bar.output); // yields "guacamole" <----
Birisi neden try_this()işe yarayıp yaramadığını anlamama yardım edebilir run_cmd()mi? FWIW, kullanmam gerekiyor child_process.spawnçünkü child_process.exec200KB tampon limiti var.
Nihai Çözüm
James White'ın cevabını kabul ediyorum, ancak bu benim için işe yarayan kodun aynısı ...
function cmd_exec(cmd, args, cb_stdout, cb_end) {
var spawn = require('child_process').spawn,
child = spawn(cmd, args),
me = this;
me.exit = 0; // Send a cb to set 1 when cmd exits
me.stdout = "";
child.stdout.on('data', function (data) { cb_stdout(me, data) });
child.stdout.on('end', function () { cb_end(me) });
}
foo = new cmd_exec('netstat', ['-rn'],
function (me, data) {me.stdout += data.toString();},
function (me) {me.exit = 1;}
);
function log_console() {
console.log(foo.stdout);
}
setTimeout(
// wait 0.25 seconds and print the output
log_console,
250);
me.stdout = "";içindecmd_exec()birleştirerek önlemek içinundefinedsonuç başlangıcına.