欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

利用NodeJS的子進程(child_process)調(diào)用系統(tǒng)命令的方法分享

 更新時間:2013年06月05日 12:52:59   作者:  
child_process即子進程可以創(chuàng)建一個系統(tǒng)子進程并執(zhí)行shell命令,在與系統(tǒng)層面的交互上挺有用處
NodeJS子進程簡介 NodeJS子進程提供了與系統(tǒng)交互的重要接口,其主要API有: 標準輸入、標準輸出及標準錯誤輸出的接口。

NodeJS子進程簡介

NodeJS 子進程提供了與系統(tǒng)交互的重要接口,其主要 API 有:

標準輸入、標準輸出及標準錯誤輸出的接口
child.stdin 獲取標準輸入
child.stdout 獲取標準輸出
child.stderr 獲取標準錯誤輸出
獲取子進程的PID:child.pid
提供生成子進程的重要方法:child_process.spawn(cmd, args=[], [options])
提供直接執(zhí)行系統(tǒng)命令的重要方法:child_process.exec(cmd, [options], callback)
提供殺死進程的方法:child.kill(signal='SIGTERM')

實例一:利用子進程獲取系統(tǒng)內(nèi)存使用情況

將以下代碼保存為 free.js:

復(fù)制代碼 代碼如下:

var spawn = require('child_process').spawn,
free = spawn('free', ['-m']);

// 捕獲標準輸出并將其打印到控制臺
free.stdout.on('data', function (data) {
console.log('標準輸出:\n' + data);
});

// 捕獲標準錯誤輸出并將其打印到控制臺
free.stderr.on('data', function (data) {
console.log('標準錯誤輸出:\n' + data);
});

// 注冊子進程關(guān)閉事件
free.on('exit', function (code, signal) {
console.log('子進程已退出,代碼:' + code);
});


執(zhí)行代碼后的結(jié)果:

$ node free.js
標準輸出:
total used free shared buffers cached
Mem: 3949 1974 1974 0 135 959
-/+ buffers/cache: 879 3070
Swap: 3905 0 3905

子進程已退出,代碼:0
以上輸出相當與在命令行執(zhí)行:free -m 命令。

通過這個簡單的例子我們已經(jīng)對子進程的使用有所了解,下面再來一個示例,用于演示exec 的使用方法。

實例二:利用子進程統(tǒng)計系統(tǒng)登錄次數(shù)

將下面代碼保存為 last.js

復(fù)制代碼 代碼如下:

var exec = require('child_process').exec,
last = exec('last | wc -l');

last.stdout.on('data', function (data) {
console.log('標準輸出:' + data);
});

last.on('exit', function (code) {
console.log('子進程已關(guān)閉,代碼:' + code);
});

執(zhí)行代碼:

$ node last.js
標準輸出:203

子進程已關(guān)閉,代碼:0
其與直接在命令行輸入:last | wc -l 的結(jié)果是一樣的。

相關(guān)文章

最新評論