Skip to content

Instantly share code, notes, and snippets.

@kjunichi
Last active March 29, 2017 01:19
Show Gist options
  • Save kjunichi/9439946 to your computer and use it in GitHub Desktop.
Save kjunichi/9439946 to your computer and use it in GitHub Desktop.
node.jsでパイプを使ったコマンドを実行するには
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