Node.js 核心特性
Node.js 基於 Chrome V8 引擎,採用事件驅動、非阻塞 I/O 模型,由 Ryan Dahl 於 2009 年發布。讓 JavaScript 成為全端語言。
- 事件驅動 — 基於 EventEmitter 模式
- 非阻塞 I/O — 高效處理並發請求
- 單執行緒事件循環 — 簡化並發模型
- npm — 全球最大的套件生態系統
模組系統
Node.js 使用 CommonJS 模組規範,也支援 ES Modules。
// CommonJS 匯出 (myModule.js)
module.exports = { greet: (name) => `Hello, ${name}!` };
// 匯入
const myModule = require('./myModule');
HTTP 伺服器
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
檔案系統與串流
const fs = require('fs');
const fsPromises = require('fs').promises;
async function readFile() {
const data = await fsPromises.readFile('file.txt', 'utf8');
console.log(data);
}
// 串流處理大型檔案
const readStream = fs.createReadStream('input.txt');
readStream.pipe(process.stdout);
熱門框架
- Express.js — 簡單靈活的 Web 框架
- NestJS — 漸進式框架,支援 TypeScript
- Fastify — 高效能框架
- Socket.io — WebSocket 即時通訊