Node.js基础
基础概念
Node.js是一个基于Chrome V8引擎的JavaScript运行环境,使用事件驱动、非阻塞I/O模型,轻量且高效。它使JavaScript可以运行在服务器端,执行文件I/O、网络I/O等操作。
核心特性
- 事件驱动: 基于事件循环的非阻塞I/O
- 单线程: 主线程处理用户请求
- 异步编程: 支持回调、Promise、async/await
- 跨平台: 支持Windows、macOS、Linux
核心模块
Node.js提供了丰富的核心模块,帮助开发者快速构建应用:
fs(文件系统)
javascript
const fs = require('fs');
// 同步读取文件
const data = fs.readFileSync('file.txt', 'utf8');
// 异步读取文件
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
http(HTTP服务器和客户端)
javascript
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
path(路径处理)
javascript
const path = require('path');
// 路径拼接
const fullPath = path.join(__dirname, 'files', 'data.txt');
// 获取文件扩展名
const ext = path.extname('file.txt'); // '.txt'
// 解析路径
const parsed = path.parse('/home/user/file.txt');
events(事件处理)
javascript
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', (arg) => {
console.log('Event occurred:', arg);
});
myEmitter.emit('event', 'Hello World');
NPM生态
NPM(Node Package Manager)是Node.js的包管理工具,拥有全球最大的开源库生态系统。
常用命令
bash
# 初始化项目
npm init
# 安装依赖
npm install package-name
npm install --save-dev package-name
# 运行脚本
npm run script-name
# 发布包
npm publish
package.json
json
{
"name": "my-project",
"version": "1.0.0",
"description": "A sample Node.js project",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js",
"test": "jest"
},
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"nodemon": "^2.0.7"
}
}
异步编程
回调函数
javascript
fs.readFile('input.txt', (err, data) => {
if (err) {
console.error('Error:', err);
return;
}
console.log('Data:', data);
});
Promise
javascript
const fs = require('fs').promises;
fs.readFile('input.txt')
.then(data => {
console.log('Data:', data);
})
.catch(err => {
console.error('Error:', err);
});
async/await
javascript
async function readFile() {
try {
const data = await fs.readFile('input.txt');
console.log('Data:', data);
} catch (err) {
console.error('Error:', err);
}
}
模块系统
CommonJS
javascript
// math.js
module.exports = {
add: (a, b) => a + b,
subtract: (a, b) => a - b
};
// main.js
const math = require('./math');
console.log(math.add(5, 3)); // 8
ES Modules
javascript
// math.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
// main.js
import { add, subtract } from './math.js';
console.log(add(5, 3)); // 8
性能优化
内存管理
- 及时释放不需要的引用
- 使用流处理大文件
- 避免内存泄漏
异步操作
- 使用Promise.all并行处理
- 合理使用async/await
- 避免回调地狱
缓存策略
- 使用Redis等缓存系统
- 合理设置缓存时间
- 实现缓存失效机制
最佳实践
错误处理
javascript
process.on('uncaughtException', (err) => {
console.error('Uncaught Exception:', err);
process.exit(1);
});
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});
日志记录
javascript
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' })
]
});
环境配置
javascript
require('dotenv').config();
const config = {
port: process.env.PORT || 3000,
database: process.env.DATABASE_URL,
apiKey: process.env.API_KEY
};