# Node.js的核心模塊有哪些
Node.js 作為基于 Chrome V8 引擎的 JavaScript 運行時,其核心模塊(Core Modules)是平臺內置的基礎功能庫,無需安裝即可直接使用。這些模塊為開發者提供了文件系統操作、網絡通信、進程管理等關鍵能力。以下是 Node.js 核心模塊的全面解析:
---
## 一、核心模塊概覽
Node.js 的核心模塊通過 `require()` 直接加載,無需路徑前綴(例如 `require('fs')`)。以下是主要模塊的分類與功能:
| 模塊名 | 作用描述 |
|----------------|----------------------------|
| `fs` | 文件系統讀寫操作 |
| `path` | 處理文件/目錄路徑 |
| `http/https` | 創建 HTTP/HTTPS 服務器和客戶端 |
| `events` | 事件觸發與監聽機制 |
| `stream` | 流式數據處理 |
| `os` | 操作系統信息查詢 |
| `util` | 實用工具函數 |
| `crypto` | 加密/解密功能 |
| `child_process`| 創建子進程 |
| `cluster` | 多進程負載均衡 |
| `dns` | 域名解析 |
| `net` | 底層網絡通信 |
| `url` | URL 解析與格式化 |
| `querystring` | 查詢字符串處理 |
| `zlib` | 數據壓縮/解壓 |
| `buffer` | 二進制數據處理 |
| `timers` | 定時器功能 |
---
## 二、重點模塊詳解
### 1. **文件系統:`fs` 模塊**
```javascript
const fs = require('fs');
// 異步讀取文件
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
// 同步寫入文件
fs.writeFileSync('output.txt', 'Hello Node.js');
http
模塊const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Server Running');
}).listen(3000);
events
模塊const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
console.log('Event triggered!');
});
myEmitter.emit('event'); // 輸出: Event triggered!
stream
、http
均繼承自 EventEmitter
stream
模塊const { Readable } = require('stream');
const myStream = new Readable({
read() {
this.push('Data chunk ');
this.push(null); // 結束流
}
});
myStream.pipe(process.stdout); // 輸出到控制臺
child_process
const { exec } = require('child_process');
exec('ls -l', (error, stdout) => {
console.log(stdout);
});
fork()
用于 CPU 密集型任務)path
模塊const path = require('path');
console.log(path.join('/tmp', 'file.txt')); // 輸出跨平臺兼容路徑
crypto
模塊const crypto = require('crypto');
const hash = crypto.createHash('sha256')
.update('password')
.digest('hex');
os
模塊const os = require('os');
console.log(os.platform()); // 輸出操作系統類型
util
模塊const util = require('util');
const sleep = util.promisify(setTimeout);
await sleep(1000); // 將回調函數轉為 Promise
promisify
、inherits
等工具Node.js 核心模塊通過 C++ 編寫,編譯為二進制文件,加載優先級最高。當與第三方模塊同名時(如 http
),始終優先加載核心模塊。
require('module').builtinModules; // 查看所有核心模塊列表
crypto
)path
)Node.js 的核心模塊是其強大功能的基石,覆蓋了以下關鍵領域:
- I/O 操作(fs
, stream
)
- 網絡通信(http
, net
)
- 系統交互(os
, child_process
)
- 安全(crypto
)
- 工具鏈(util
, path
)
掌握這些模塊能顯著提升開發效率,避免重復造輪子。建議通過官方文檔深入每個模塊的細節應用場景。
擴展閱讀:
- Node.js 官方文檔
- 《Node.js 設計模式》- Mario Casciaro “`
注:此文檔約 1500 字,實際字數可能因格式調整略有差異??赏ㄟ^代碼示例擴展或補充模塊應用場景進一步增加篇幅。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。