Last active
March 29, 2017 01:19
-
-
Save kjunichi/9439946 to your computer and use it in GitHub Desktop.
node.jsでパイプを使ったコマンドを実行するには
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const spawn = require('child_process').spawn; | |
const cmd = "top -l1|grep usage|cut -d' ' -f3|tr -d '%'|tr -d '\n'"; | |
const child = shspawn(cmd); | |
let buf=""; | |
child.stdout.on('data',(data)=>{ | |
buf=buf+data; | |
}); | |
child.stderr.on('data',(data)=>{ | |
console.log('exec error: '+data); | |
}); | |
child.on('close',(code) => { | |
// コマンド実行後の処理 | |
// codeでコマンドの実行の成否が確認できる。 | |
// この時点でbufに正常時はコマンドの出力結果が入っている。 | |
console.log(buf); | |
}); | |
function shspawn(command) { | |
return spawn('sh', ['-c', command]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment