主题
Node.js 核心模块
Node.js 内置了丰富的核心模块(无需安装即可使用),覆盖文件、网络、路径、流、事件等基础设施。
作者:yanshaodong
fs —— 文件系统
javascript
const fs = require('fs')
const fsp = require('fs').promises
// 回调式
fs.readFile('a.txt', 'utf8', (err, data) => {
if (err) throw err
console.log(data)
})
// Promise 式(推荐)
const main = async () => {
const data = await fsp.readFile('a.txt', 'utf8')
await fsp.writeFile('b.txt', data)
}常用 API:readFile / writeFile(一次性)、createReadStream / createWriteStream(流式)、mkdir / rm / stat。
path —— 路径处理
javascript
const path = require('path')
path.join(__dirname, 'data', 'a.json') // 跨平台拼接
path.resolve('src', 'index.js') // 解析为绝对路径
path.basename('/a/b/c.txt') // c.txt
path.extname('/a/b/c.txt') // .txt始终使用
path.join而非字符串拼接,避免 Windows 反斜杠问题。
http —— HTTP 服务
javascript
const http = require('http')
const { URL } = require('url')
const server = http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost')
if (req.method === 'GET' && url.pathname === '/api/hello') {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ msg: 'hello' }))
} else {
res.writeHead(404)
res.end('Not Found')
}
})
server.listen(3000)stream —— 流
流是处理大文件和高并发 I/O 的核心,避免一次性加载到内存。
javascript
const fs = require('fs')
// 管道:读取流 → 写入流
fs.createReadStream('big.iso')
.pipe(fs.createWriteStream('copy.iso'))
// 背压自动处理,无需手动控制流速四种流类型:Readable、Writable、Duplex、Transform(如压缩、加解密)。
events —— 事件触发器
Node.js 异步基石,很多核心模块都继承自 EventEmitter。
javascript
const EventEmitter = require('events')
const emitter = new EventEmitter()
emitter.on('data', (payload) => {
console.log('收到:', payload)
})
emitter.emit('data', { id: 1 })buffer 与 buffer/string
Buffer 用于操作二进制数据(文件、网络包)。
javascript
const buf = Buffer.from('你好', 'utf8')
console.log(buf.length) // 字节数(中文 3 字节)
console.log(buf.toString('hex'))process —— 进程信息
javascript
process.pid // 进程 ID
process.env.NODE_ENV // 环境变量
process.argv // 命令行参数
process.on('uncaughtException', (err) => { /* 兜底 */ })
process.on('SIGTERM', () => { /* 优雅退出 */ })核心模块速览
| 模块 | 用途 |
|---|---|
fs / fs/promises | 文件读写 |
path | 路径处理 |
http / https | HTTP 服务与请求 |
stream | 流式 I/O |
events | 事件机制 |
crypto | 加密哈希 |
os | 操作系统信息 |
util | 工具(如 promisify) |
child_process | 创建子进程 |
worker_threads | 多线程计算 |
作者:yanshaodong