• Node.js Video Tutorials

Node.js - 應用擴充套件



Node.js 應用的可擴充套件性是指它處理伺服器上不斷增加的工作負載的能力,即處理來自客戶端的更多請求。Node.js 應用可以使用子程序來解決這個問題。子程序是 Node.js 執行時的單獨例項,可以由主程序生成和管理。這樣生成的子程序可以並行執行特定任務,從而提高應用程式的整體效能和可擴充套件性。

child_process 模組是 Node.js 執行時的核心模組之一。此模組提供各種方法來建立、管理和與子程序通訊,尤其是在基於多核 CPU 的系統上。

子程序始終具有三個流:child.stdin、child.stdout 和 child.stderr。這些流可以與父程序的流共享。

child_process 模組有以下三種主要方法來建立子程序。

  • exec − child_process.exec 方法在 shell/控制檯中執行命令並緩衝輸出。

  • spawn − child_process.spawn 啟動一個具有給定命令的新程序。

  • fork − child_process.fork 方法是 spawn() 的一個特例,用於建立子程序。

exec() 方法

child_process.exec 方法在 shell 中執行命令並緩衝輸出。它具有以下簽名:

child_process.exec(command[, options], callback)

引數

  • command − 要執行的命令,使用空格分隔的引數。

  • options − cwd- 子程序的當前工作目錄,以及 env - 環境鍵值對

    • encoding − 編碼字串(預設值:'utf8')

    • shell − 用於執行命令的 shell(UNIX 上預設為 '/bin/sh',Windows 上預設為 'cmd.exe',shell 應該理解 UNIX 上的 -c 開關或 Windows 上的 /s /c。在 Windows 上,命令列解析應與 cmd.exe 相容。)

    • timeout − 預設值:0

    • maxBuffer − 預設值:200*1024

    • killSignal − 預設值:'SIGTERM'

    • uid − 設定程序的使用者標識。

    • gid − 設定程序的組標識。

    • callback − 一個具有三個引數 error、stdout 和 stderr 的函式,在程序終止時使用輸出呼叫。

exec() 方法返回一個具有最大大小的緩衝區,等待程序結束並嘗試一次返回所有緩衝資料。

示例

讓我們建立兩個名為 child.js 和 main.js 的 js 檔案:

檔案:child.js

console.log("Starting Child Process-" + process.argv[2]);
console.log("Child Process-" + process.argv[2] + " executed." );

檔案:main.js

const fs = require('fs');
const child_process = require('child_process');

for(var i=0; i<3; i++) {
   var childprocess = child_process.exec('node child.js '+i,function 
      (error, stdout, stderr) {
      
      if (error) {
         console.log(error.stack);
         console.log('Error code: '+error.code);
         console.log('Signal received: '+error.signal);
      }
      console.log('stdout: ' + stdout);
      console.log('stderr: ' + stderr);
   });

   childprocess.on('exit', function (code) {
      console.log('Child process exited with exit code '+code);
   });
}

現在執行 main.js 檢視結果:

Child process exited with exit code 0
stdout: Starting Child Process-0
Child Process-0 executed.

stderr:
Child process exited with exit code 0
stdout: Starting Child Process-1
Child Process-1 executed.

stderr:
Child process exited with exit code 0
stdout: Starting Child Process-2
Child Process-2 executed.

stderr:

spawn() 方法

child_process.spawn 方法使用給定的命令啟動一個新程序。

child_process.spawn(command[, args][, options])

第一個引數是子程序要執行的命令。可以向其傳遞一個或多個引數。options 引數可能具有以下一個或多個屬性:

  • cwd (字串) 子程序的當前工作目錄。

  • env (物件) 環境鍵值對。

  • stdio (陣列) 字串 子程序的 stdio 配置。

  • customFds (陣列) 已棄用 子程序用於 stdio 的檔案描述符。

  • detached (布林值) 子程序將成為程序組領導者。

  • uid (數字) 設定程序的使用者標識。

  • gid (數字) 設定程序的組標識。

spawn() 方法返回流 (stdout & stderr),當程序返回大量資料時應使用它。spawn() 在程序開始執行後立即開始接收響應。

示例

與之前的示例一樣,建立 child.js 和 main.js 檔案。

child.js

console.log("Starting Child Process-" + process.argv[2]);
console.log("Child Process-" + process.argv[2] + " executed." );

main.js

const fs = require('fs');
const child_process = require('child_process');

for(var i=0; i<3; i++) {
var childprocess = child_process.spawn('node', ['child.js', i]);

   childprocess.stdout.on('data', function (data) {
      console.log('stdout: ' + data);
   });

   childprocess.on('exit', function (code) {
      console.log('Child process exited with exit code '+code);
   });
}

輸出

stdout: Starting Child Process-0

stdout: Child Process-0 executed.

Child process exited with exit code 0
stdout: Starting Child Process-1

stdout: Child Process-1 executed.

stdout: Starting Child Process-2

stdout: Child Process-2 executed.

Child process exited with exit code 0
Child process exited with exit code 0

fork() 方法

child_process.fork 方法是 spawn() 的一個特例,用於建立 Node 程序。它具有以下語法:

child_process.fork(modulePath[, args][, options])

引數

第一個引數是子程序要執行的模組。您可以向模組傳遞其他引數。選項與 spawn() 方法中的選項相同。

示例

與之前的示例一樣,建立 child.js 和 main.js 檔案。

child.js

console.log("Starting Child Process-" + process.argv[2]);
console.log("Child Process-" + process.argv[2] + " executed." );

main.js

const fs = require('fs');
const child_process = require('child_process');

for(var i=0; i<3; i++) {
   var childprocess = child_process.fork("child.js", [i]);	

   childprocess.on('close', function (code) {
      console.log('child process exited with code ' + code);
   });
}

輸出

Starting Child Process-0
Child Process-0 executed.
Starting Child Process-2
Child Process-2 executed.
Starting Child Process-1
Child Process-1 executed.
child process exited with code 0
child process exited with code 0
child process exited with code 0

execFile() 方法

child_process.execFile() 函式類似於 exec() 方法,不同之處在於它預設情況下不會生成 shell。它比 exec() 更有效率,因為它直接將指定的可執行檔案作為新程序生成。

語法

child_process.execFile(command [, args][, options][, callback])

引數

  • command − 接受一個字串,指定要執行的命令的名稱或路徑。

  • args − 字串引數列表。

  • options − 一些可用的選項包括 cwd、env、encoding、shell、timeout 等

  • callback − 當程序終止時呼叫回撥函式。此函式的引數分別是 error、stdout 和 stderr。

廣告