利用NodeJS的子進程(child_process)調用系統命令的方法分享

來源:互聯網
上載者:User

NodeJS子進程簡介 NodeJS子進程提供了與系統互動的重要介面,其主要API有: 標準輸入、標準輸出及標準錯誤輸出的介面。

NodeJS子進程簡介

NodeJS 子進程提供了與系統互動的重要介面,其主要 API 有:

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

執行個體一:利用子進程擷取系統記憶體使用量情況

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

複製代碼 代碼如下:
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);
});

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


執行代碼後的結果:

$ 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
以上輸出相當與在命令列執行:free -m 命令。

通過這個簡單的例子我們已經對子進程的使用有所瞭解,下面再來一個樣本,用於示範exec 的使用方法。

執行個體二:利用子進程統計系統登入次數

將下面代碼儲存為 last.js

複製代碼 代碼如下:
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('子進程已關閉,代碼:' + code);
});

執行代碼:

$ node last.js
標準輸出:203

子進程已關閉,代碼:0
其與直接在命令列輸入:last | wc -l 的結果是一樣的。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.