NodeJS子進(jìn)程簡介 NodeJS子進(jìn)程提供了與系統(tǒng)交互的重要接口,其主要API有: 標(biāo)準(zhǔn)輸入、標(biāo)準(zhǔn)輸出及標(biāo)準(zhǔn)錯誤輸出的接口。
NodeJS子進(jìn)程簡介
NodeJS 子進(jìn)程提供了與系統(tǒng)交互的重要接口,其主要 API 有:
標(biāo)準(zhǔn)輸入、標(biāo)準(zhǔn)輸出及標(biāo)準(zhǔn)錯誤輸出的接口
child.stdin 獲取標(biāo)準(zhǔn)輸入
child.stdout 獲取標(biāo)準(zhǔn)輸出
child.stderr 獲取標(biāo)準(zhǔn)錯誤輸出
獲取子進(jìn)程的PID:child.pid
提供生成子進(jìn)程的重要方法:child_process.spawn(cmd, args=[], [options])
提供直接執(zhí)行系統(tǒng)命令的重要方法:child_process.exec(cmd, [options], callback)
提供殺死進(jìn)程的方法:child.kill(signal='SIGTERM')
實例一:利用子進(jìn)程獲取系統(tǒng)內(nèi)存使用情況
將以下代碼保存為 free.js:
復(fù)制代碼 代碼如下:
var spawn = require('child_process').spawn,
free = spawn('free', ['-m']);
// 捕獲標(biāo)準(zhǔn)輸出并將其打印到控制臺
free.stdout.on('data', function (data) {
console.log('標(biāo)準(zhǔn)輸出:/n' + data);
});
// 捕獲標(biāo)準(zhǔn)錯誤輸出并將其打印到控制臺
free.stderr.on('data', function (data) {
console.log('標(biāo)準(zhǔn)錯誤輸出:/n' + data);
});
// 注冊子進(jìn)程關(guān)閉事件
free.on('exit', function (code, signal) {
console.log('子進(jìn)程已退出,代碼:' + code);
});
復(fù)制代碼 代碼如下:
var exec = require('child_process').exec,
last = exec('last | wc -l');
last.stdout.on('data', function (data) {
console.log('標(biāo)準(zhǔn)輸出:' + data);
});
last.on('exit', function (code) {
console.log('子進(jìn)程已關(guān)閉,代碼:' + code);
});
新聞熱點
疑難解答
圖片精選