Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux管理 >> Linux維護

用 Node.js 執行 Linux 命令:exec 與 execFile 實作

Node.js 除了寫 Web,也能作為自動化的骨架去呼叫系統指令。靠著 child_process 模組,非同步執行 shell 命令既快速又不阻塞。

最簡版本

var sys = require('sys');
var exec = require('child_process').exec;

// 執行 pwd
exec("pwd", function (error, stdout, stderr) {
  sys.print('stdout: ' + stdout);
  sys.print('stderr: ' + stderr);
  if (error !== null) {
    console.log('exec error: ' + error);
  }
});

回呼函式的三個參數分別是錯誤物件、標準輸出與標準錯誤,養成檢查 error 的習慣能省下很多除錯時間。

封裝成可重複使用的模組

var process = require('child_process');

// 直接執行指令
exports.createDir = function () {
  process.exec('cd testweb && mkdir mydir', function (error, stdout, stderr) {
    if (error !== null) {
      console.log('exec error: ' + error);
    }
  });
};

// 執行外部程式
exports.openApp = function () {
  process.execFile('/path/to/aaa.sh', null, { cwd: '/path/to/' }, function (error, stdout, stderr) {
    if (error !== null) {
      console.log('exec error: ' + error);
    }
  });
};

幾個實務選擇

命令寫死雖然簡單,但缺乏彈性。若需要動態參數,把邏輯寫成 shell 腳本再呼叫會更安全,也能避免字串拼接帶來的注入風險。此外,exec 會經過 shell 解析,execFile 則直接執行檔案而不啟動 shell,處理不可信輸入時應優先選擇後者;需要串接多段輸出時,也可以考慮 spawn 以取得串流。

Copyright © Linux教程網 All Rights Reserved