使用 child_process.exec 實現
child_process即子進程可以創建一個系統子進程並執行shell命令,在與系統層面的交互上非常有用
NodeJS子進程提供了與系統交互的重要接口,其主要API有: 標准輸入、標准輸出及標准錯誤輸出的接口
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')
使用child_process模塊的步驟:
1.調用系統命令行
2.打開第三方軟件
3.打開第三方軟件並實現通信
示例:
調用命令行ipconfig獲取系統相關IP信息
(1)使用exec
"use strict"; var exec = require("child_process").exec; module.exports = function myTest() { return new Promise(function(resolve, reject) { var cmd = "ipconfig"; exec(cmd,{ maxBuffer: 1024 * 2000 }, function(err, stdout, stderr) { if (err) { console.log(err); reject(err); } else if (stderr.lenght > 0) { reject(new Error(stderr.toString())); } else { console.log(stdout); resolve(); } }); }); };
(2)使用spawn
var spawn = require("child_process").spawn; module.exports = function myTest() { return new Promise(function(resolve, reject) { var cmd = "ipconfig"; var result = spawn('cmd.exe', ['/s', '/c', 'ipconfig']); result.on('close', function(code) { console.log('child process exited with code :' + code); }); result.stdout.on('data', function(data) { console.log('stdout: ' + data); }); result.stderr.on('data', function(data) { console.log('stderr: ' + data); reject(new Error(stderr.toString())); }); resolve(); }); };
說明:
exec是在執行完成后返回一個完整的buffer,通過返回的buffer去識別完成狀態
spawn在執行時會返回一個stdout和stderr流對象,為邊執行邊返回。在執行完成后會拋出close事件監聽,並返回狀態碼,通過狀態碼可以知道子進程是否順利執行
