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 应用程序。
