
- Node.js 教程
- Node.js - 首頁
- Node.js - 簡介
- Node.js - 環境設定
- Node.js - 第一個應用程式
- Node.js - REPL 終端
- Node.js - 命令列選項
- Node.js - 包管理器 (NPM)
- Node.js - 回撥函式概念
- Node.js - 上傳檔案
- Node.js - 傳送郵件
- Node.js - 事件
- Node.js - 事件迴圈
- Node.js - 事件發射器
- Node.js - 偵錯程式
- Node.js - 全域性物件
- Node.js - 控制檯
- Node.js - 程序
- Node.js - 應用程式擴充套件
- Node.js - 打包
- Node.js - Express 框架
- Node.js - RESTful API
- Node.js - 緩衝區
- Node.js - 流
- Node.js - 檔案系統
- Node.js MySQL
- Node.js - MySQL 入門
- Node.js - MySQL 建立資料庫
- Node.js - MySQL 建立表
- Node.js - MySQL 插入資料
- Node.js - MySQL 從表中選擇資料
- Node.js - MySQL WHERE 條件
- Node.js - MySQL ORDER BY 排序
- Node.js - MySQL 刪除資料
- Node.js - MySQL 更新資料
- Node.js - MySQL 聯接
- Node.js MongoDB
- Node.js - MongoDB 入門
- Node.js - MongoDB 建立資料庫
- Node.js - MongoDB 建立集合
- Node.js - MongoDB 插入資料
- Node.js - MongoDB 查詢資料
- Node.js - MongoDB 查詢
- Node.js - MongoDB 排序
- Node.js - MongoDB 刪除資料
- Node.js - MongoDB 更新資料
- Node.js - MongoDB 限制結果
- Node.js - MongoDB 聯接
- Node.js 模組
- Node.js - 模組
- Node.js - 內建模組
- Node.js - 實用程式模組
- Node.js - Web 模組
- Node.js 有用資源
- Node.js - 快速指南
- Node.js - 有用資源
- Node.js - 討論
Node.js - 程序
Node.js 中的 process 物件是一個全域性物件,儘管它是在 process 模組中定義的。它是一個 EventEmitter 類的例項。process 物件提供有關當前 Node.js 程序的資訊。藉助與此物件關聯的許多方法和屬性,可以控制當前的 Node.js 程序。
程序事件
process 物件是 EventEmitter 的一個例項,併發出以下事件:
序號 | 事件 & 描述 |
---|---|
1 |
exit 當程序即將退出時發出。此時無法阻止事件迴圈退出,並且一旦所有 exit 監聽器執行完畢,程序將退出。 |
2 |
beforeExit 當 Node.js 清空其事件迴圈並且沒有其他內容要排程時發出此事件。通常,當沒有計劃工作時,Node.js 會退出,但是 'beforeExit' 的監聽器可以進行非同步呼叫,並導致 Node.js 繼續執行。 |
3 |
uncaughtException 當異常冒泡回事件迴圈時發出。如果為該異常添加了監聽器,則不會發生預設操作(即列印堆疊跟蹤並退出)。 |
4 |
warning 每當 Node.js 發出程序警告時,都會發出 'warning' 事件。程序警告類似於錯誤,因為它描述了需要提請使用者注意的異常情況。 |
5 |
訊號事件 當程序收到訊號(例如 SIGINT、SIGHUP 等)時發出。 |
示例
在以下程式碼中,process 物件的 beforeExit 事件與一個回撥箭頭函式相關聯。類似地,exit 事件呼叫另一個回撥函式。beforeExit 上的函式首先執行,然後是 exit 事件上的函式。
process.on('beforeExit', (code) => { console.log('A beforeExit event occured with code: ', code); }); process.on('exit', (code) => { console.log('Process exit event with code: ', code); }); console.log('This message is displayed first.');
輸出
This message is displayed first. A beforeExit event occured with code: 0 Process exit event with code: 0
注意 監聽器函式只能執行同步操作。Node.js 程序將在呼叫 'exit' 事件監聽器後立即退出,導致事件迴圈中仍排隊的任何其他工作被放棄。例如,在以下示例中,超時將永遠不會發生:
示例
process.on('exit', function(code) { // Following code will never execute. setTimeout(function() { console.log("This will not run"); }, 0); console.log('About to exit with code:', code); }); console.log("Program Ended");
輸出
Program Ended About to exit with code: 0
程序方法
abort()
abort() 方法立即終止當前程序,然後建立一個核心檔案。
示例
以下程式每隔一秒鐘向控制檯列印一條訊息,並在 5 秒後終止迴圈,因為呼叫了 abort() 函式。
const abortfunction = () => { console.log('Start...'); // It prints the message after every 1 second setInterval((function() { return console.log('Hello World'); }), 1000); // It calls process.abort() after 5 seconds setTimeout((function() { return process.abort(); }), 5000); }; abortfunction();
輸出
Start... Hello World Hello World Hello World Hello World
終止後會輸出一個較長的核心檔案。
chdir()
此方法更改 Node.js 程序的當前工作目錄,或者如果這樣做失敗(例如,如果指定的目錄不存在),則丟擲異常。
cwd()
process.cwd() 方法返回 Node.js 程序的當前工作目錄。
示例
console.log(`Starting directory: ${process.cwd()}`); try { process.chdir('NewNodeApp'); console.log(`New directory: ${process.cwd()}`); } catch (err) { console.error(`chdir: ${err}`); }
輸出
Starting directory: D:\nodejs New directory: D:\nodejs\NewNodeApp
如果找不到目錄,則輸出如下:
Starting directory: D:\nodejs chdir: Error: ENOENT: no such file or directory, chdir 'D:\nodejs' -> 'NewDir'
exit()
此方法以程式碼 exit 狀態同步終止當前程序(預設為 'success' 程式碼 0)。Node.js 只有在所有 'exit' 事件監聽器都被呼叫後才會終止。
示例
console.log('Code running'); process.on('exit', function(code) { return console.log(`exiting with the error code : ${code}`); }); setTimeout((function() { return process.exit(0); //after 5 sec }), 5000);
輸出
Code running exiting with the error code : 0
kill()
此方法終止當前程序並向由 pid 標識的程序傳送訊號。
kill(pid[, signal])
引數
pid:程序 ID
signal:要傳送的訊號,可以是字串或數字。預設值:'SIGTERM'。
訊號名稱是字串,例如 'SIGINT' 或 'SIGHUP'。
示例
以下程式碼獲取當前程序的 pid。它等待足夠長的時間,然後正常退出。在此期間,如果您透過按 ctrl-C 發出 SIGINT 訊號,則程序不會終止。
const pid = process.pid; console.log(`Process ID: ${pid}`); process.on('SIGHUP', () => console.log('Received: SIGHUP')); process.on('SIGINT', () => console.log('Received: SIGINT')); setTimeout(() => {}, 100000); // keep process alive setTimeout((function() { return process.kill(pid, 'SIGINT'); //after 5 sec }), 5000);
終端在每次按下 ctrlC 時顯示程序 ID 和 Received: SIGINT。在另外 5 秒的超時後,呼叫 kill() 方法,該方法終止程序
Process ID: 1776 Received: SIGINT
memoryUsage()
此函式返回一個物件,該物件以位元組為單位描述 Node.js 程序的記憶體使用情況。
示例
console.log(process.memoryUsage());
輸出
{ rss: 24768512, heapTotal: 4079616, heapUsed: 3153848, external: 1097184, arrayBuffers: 10519 }
nextTick()
此函式將回調函式的執行推遲到下一個事件迴圈迭代。
nextTick(callback[, ...args])
此函式是 Node.js 非同步 API 中事件迴圈的重要組成部分。在 Node.js 中,事件迴圈的每次迭代都稱為一個 tick。要安排回撥函式在事件迴圈的下一次迭代中被呼叫,我們使用 process.nextTick()。
示例
console.log('start'); process.nextTick(() => { console.log('nextTick callback executed in next iteration'); }); console.log('scheduled');
輸出
start scheduled nextTick callback executed in next iteration
程序屬性
process.arch
編譯 Node.js 二進位制檔案的作業系統 CPU 架構。
可能的值為:
'arm',
'arm64',
'ia32',
'loong64',
'mips',
'mipsel',
'ppc',
'ppc64',
'riscv64',
's390',
's390x',
'x64'
示例
console.log(`This processor architecture is ${process.arch}`);
輸出
This processor architecture is x64
process.argv
此屬性返回一個數組,其中包含啟動 Node.js 程序時傳遞的命令列引數。您可以將引數傳遞到要從命令列執行的指令碼中。這些引數儲存在一個數組 process.argv 中。陣列中的第 0 個元素是 node 可執行檔案,第一個元素是 JavaScript 檔案,後面跟著傳遞的引數。
將以下指令碼另存為 hello.js 並從命令列執行它,從命令列向其傳遞一個字串引數。
const args = process.argv; console.log(args); const name = args[2]; console.log("Hello,", name);
在終端中,輸入
PS D:\nodejs> node hello.js TutorialsPoint [ 'C:\\nodejs\\node.exe', 'c:\\nodejs\\a.js', 'TutorialsPoint' ] Hello, TutorialsPoint
process.env
屬性返回一個包含環境變數的物件。
示例
const processEnvKeys = Object.keys(process.env); processEnvKeys.forEach((key) => { console.log(`${key}: ${process.env[key]}`); });
輸出
SystemDrive: C: SystemRoot: C:\WINDOWS TEMP: C:\Users\mlath\AppData\Local\Temp TMP: C:\Users\mlath\AppData\Local\Temp USERDOMAIN: GNVBGL3 USERDOMAIN_ROAMINGPROFILE: GNVBGL3 USERNAME: mlath USERPROFILE: C:\Users\mlath windir: C:\WINDOWS ZES_ENABLE_SYSMAN: 1 TERM_PROGRAM: vscode TERM_PROGRAM_VERSION: 1.84.2 LANG: en_US.UTF-8 COLORTERM: truecolor VSCODE_INJECTION: 1 VSCODE_NONCE: b8069509-e0f5-4bbd-aac9-fc448279b154
您還可以從命令列設定環境變數。在 node 可執行檔名之前為一個或多個變數賦值。
USER_ID=101 USER_NAME=admin node app.js
在指令碼內部,環境變數作為 process.env 物件的屬性可用
process.env.USER_ID; // "101" process.env.USER_NAME; // "admin"
process.pid
屬性返回程序的 PID。
示例
const { pid } = require('node:process'); console.log(`This process is pid ${pid}`);
輸出
This process is pid 16312
process.platform
此屬性返回一個字串,用於標識作業系統。
可能的值為:
'aix'
'darwin'
'freebsd'
'linux'
'openbsd'
'sunos'
'win32'
process.version
此屬性包含 Node.js 版本字串。
示例
console.log(`Version: ${process.version}`);
輸出
Version: v20.9.0