Node.js 使用手冊
基礎使用
建立第一個 Node.js 應用
Node.js 應用程式通常以 .js 檔案副檔名儲存。最簡單的 "Hello World" 應用如下:
// hello.js
console.log('Hello World!');
在終端機中執行:
node hello.js
模組系統
Node.js 支援兩種模組系統:CommonJS 和 ECMAScript Modules (ESM)。
CommonJS 模組(預設)
// math.js
function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
// 匯出模組
module.exports = { add, multiply };
// 或者
exports.add = add;
exports.multiply = multiply;
在其他檔案中使用:
// app.js
const math = require('./math');
// 或者解構匯入
const { add, multiply } = require('./math');
console.log(math.add(2, 3)); // 輸出: 5
console.log(multiply(4, 5)); // 輸出: 20
ECMAScript Modules (ESM)
// math.mjs 或 package.json 中設定 "type": "module"
export function add(a, b) {
return a + b;
}
export function multiply(a, b) {
return a * b;
}
// 預設匯出
export default function subtract(a, b) {
return a - b;
}
在其他檔案中使用:
// app.mjs
import { add, multiply } from './math.js';
import subtract from './math.js';
console.log(add(2, 3)); // 輸出: 5
console.log(multiply(4, 5)); // 輸出: 20
console.log(subtract(10, 3)); // 輸出: 7
內建模組
Node.js 提供了許多內建模組,無需安裝即可使用:
- fs: 檔案系統操作
- http: HTTP 伺服器和用戶端
- path: 路徑操作
- os: 作業系統資訊
- events: 事件處理
- stream: 串流處理
- buffer: 二進位資料處理
- crypto: 加密功能
- child_process: 子處理程序管理
- cluster: 叢集支援
範例 - 建立 HTTP 伺服器:
const http = require('node:http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello from Node.js Server!');
});
server.listen(3000, '127.0.0.1', () => {
console.log('Server running at http://127.0.0.1:3000/');
});
套件管理 (npm)
初始化專案
# 互動式初始化
npm init
# 使用預設設定
npm init -y
這會建立 package.json 檔案,用於管理專案相依性和中繼資料。
package.json 結構
{
"name": "my-app",
"version": "1.0.0",
"description": "My Node.js application",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js",
"test": "jest"
},
"dependencies": {
"express": "^4.18.2"
},
"devDependencies": {
"nodemon": "^3.0.1",
"jest": "^29.7.0"
},
"engines": {
"node": ">=18.0.0"
}
}
安裝相依性
# 安裝生產相依性
npm install express
npm i express
# 安裝開發相依性
npm install --save-dev jest
npm i -D jest
# 全域安裝
npm install -g nodemon
npm i -g nodemon
# 安裝特定版本
npm install [email protected]
# 安裝最新版本
npm install express@latest
# 從 package.json 安裝所有相依性
npm install
執行指令稿
在 package.json 中定義指令稿:
{
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js",
"test": "jest",
"build": "webpack --mode production",
"lint": "eslint ."
}
}
執行指令稿:
# 執行 start 指令稿
npm start
# 執行其他指令稿
npm run dev
npm run test
npm run build
npm run lint
npm 設定
# 查看設定
npm config list
# 設定設定
npm config set registry https://registry.npmmirror.com
# 刪除設定
npm config delete registry
# 查看特定設定
npm config get registry
非同步程式設計
回呼函式 (Callback)
const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
Promise
const fs = require('fs').promises;
// 使用 Promise
fs.readFile('file.txt', 'utf8')
.then(data => {
console.log(data);
})
.catch(err => {
console.error(err);
});
// 或者使用 async/await
async function readFile() {
try {
const data = await fs.readFile('file.txt', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
}
async/await
現代 Node.js 開發推薦使用 async/await 語法:
async function processData() {
try {
const users = await getUsers();
const processed = await processUsers(users);
await saveResults(processed);
console.log('Processing completed!');
} catch (error) {
console.error('Error:', error);
throw error; // 重新拋出錯誤或返回預設值
}
}
// 平行執行多個非同步操作
async function fetchMultipleData() {
try {
const [users, posts, comments] = await Promise.all([
fetchUsers(),
fetchPosts(),
fetchComments()
]);
return { users, posts, comments };
} catch (error) {
console.error('Error fetching data:', error);
}
}
除錯工具
內建除錯器
# 啟動除錯模式
node --inspect app.js
# 在第一行設定中斷點
node --inspect-brk app.js
# 指定除錯連接埠
node --inspect=9229 app.js
使用 Chrome DevTools
- 執行
node --inspect app.js - 開啟 Chrome 瀏覽器
- 造訪
chrome://inspect - 點選 "Open dedicated DevTools for Node"
VS Code 除錯
建立 .vscode/launch.json 檔案:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"skipFiles": ["<node_internals>/**"],
"program": "${workspaceFolder}/app.js"
}
]
}
日誌記錄
使用 console.log() 進行基本日誌記錄,或使用專門的日誌函式庫:
Winston
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.simple()
}));
}
logger.info('Hello world!');
Bunyan
const bunyan = require('bunyan');
const log = bunyan.createLogger({name: 'myapp'});
log.info('Hello world!');
log.error('Something went wrong!');
效能優化
避免阻塞操作
始終使用非同步方法處理 I/O 操作:
// ❌ 錯誤:阻塞操作
const data = fs.readFileSync('large-file.txt');
// ✅ 正確:非阻塞操作
const data = await fs.promises.readFile('large-file.txt');
// ✅ 更好:使用串流處理大檔案
const stream = fs.createReadStream('large-file.txt');
使用叢集模式
利用多核心處理器:
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
if (cluster.isPrimary) {
console.log(`主處理程序 ${process.pid} 正在執行`);
// 衍生工作處理程序
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`工作處理程序 ${worker.process.pid} 已退出`);
// 可以在這裡重新啟動工作處理程序
cluster.fork();
});
} else {
// 工作處理程序可以共用任何 TCP 連線
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
console.log(`工作處理程序 ${process.pid} 已啟動`);
}
使用串流處理大檔案
const fs = require('fs');
// 讀取大檔案
const readStream = fs.createReadStream('large-input.txt');
const writeStream = fs.createWriteStream('large-output.txt');
// 管道操作
readStream.pipe(writeStream);
// 處理串流事件
readStream.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data.`);
});
readStream.on('end', () => {
console.log('Finished reading file.');
});
readStream.on('error', (err) => {
console.error('Error reading file:', err);
});
最佳實務
1. 使用嚴格模式
在檔案頂部新增 'use strict'; 或使用 ES modules(自動啟用嚴格模式)。
2. 錯誤處理
始終處理可能的錯誤,使用 try-catch 包裝 async/await 程式碼。
3. 環境變數管理
使用 .env 檔案管理設定(不要提交到版本控制):
// .env
DATABASE_URL=your-database-url
API_KEY=your-api-key
NODE_ENV=development
// app.js
require('dotenv').config();
const dbUrl = process.env.DATABASE_URL;
const isProduction = process.env.NODE_ENV === 'production';
4. 程式碼格式化和品質
使用 ESLint 和 Prettier 保持程式碼一致性:
// .eslintrc.json
{
"extends": ["eslint:recommended", "prettier"],
"parserOptions": {
"ecmaVersion": 2020,
"sourceType": "module"
},
"env": {
"node": true,
"es6": true
}
}
5. 測試
撰寫單元測試和整合測試:
// test/math.test.js
const { add, multiply } = require('../math');
test('adds 1 + 2 to equal 3', () => {
expect(add(1, 2)).toBe(3);
});
test('multiplies 2 * 3 to equal 6', () => {
expect(multiply(2, 3)).toBe(6);
});
6. 安全性
- 定期更新相依性:
npm audit和npm audit fix - 驗證使用者輸入
- 使用 HTTPS
- 避免 eval() 和類似的危險函式
7. 效能監控
- 使用內建效能鉤子:
perf_hooks - 監控記憶體使用:
process.memoryUsage() - 使用 APM 工具如 New Relic、Datadog
常用命令
# 查看 Node.js 版本
node --version
node -v
# 查看 npm 版本
npm --version
npm -v
# 列出全域安裝的套件
npm list -g --depth=0
# 更新 npm
npm install -g npm
# 清除 npm 快取
npm cache clean --force
# 查看 Node.js 設定
node --help
npm config list
# 執行 REPL
node
# 執行單行程式碼
node -e "console.log('Hello World!')"
透過掌握這些核心概念和最佳實務,您將能夠高效地開發和維護 Node.js 應用程式。
