JavaScript (Node.js) 标准库:完整概述
Node.js 是一个基于 Google V8 引擎构建的 JavaScript 运行时环境。与浏览器端的 JavaScript 不同,Node.js 提供了强大的内置标准库,允许开发者处理文件系统、网络、数据流、加密以及许多其他功能。在本文中,我们将详细介绍每个 Node.js 开发者都必须掌握的关键标准库模块。
1. fs 模块 (File System)
fs 模块提供了与文件系统交互的 API。它同时支持同步和异步操作。
- 读取文件:
const fs = require('fs');
// 异步读取fs.readFile('example.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data);});
// 同步读取const data = fs.readFileSync('example.txt', 'utf8');console.log(data);- 写入文件:
const fs = require('fs');
fs.writeFile('output.txt', 'Привет, мир!', (err) => { if (err) throw err; console.log('文件已保存');});该模块还支持目录、流和权限管理。
2. path 模块 (路径处理)
path 模块简化了文件路径的操作,并确保了跨平台的兼容性。
const path = require('path');
const fullPath = '/users/docs/file.txt';console.log(path.dirname(fullPath)); // /users/docsconsole.log(path.basename(fullPath)); // file.txtconsole.log(path.extname(fullPath)); // .txt
// 路径拼接const newPath = path.join('/users', 'docs', 'file.txt');console.log(newPath); // /users/docs/file.txt3. http 模块 (HTTP 服务器和客户端)
使用 http 模块,无需第三方库即可创建 Web 服务器和发送 HTTP 请求。
- 简单的 HTTP 服务器:
const http = require('http');
const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('来自 Node.js 的问候!');});
server.listen(3000, () => { console.log('服务器已启动,端口 3000');});- HTTP 请求 (客户端):
const http = require('http');
http.get('http://api.example.com/data', (res) => { let data = ''; res.on('data', chunk => data += chunk); res.on('end', () => console.log(data));});4. stream 模块 (数据流)
流允许分块处理大量数据,而无需将其全部加载到内存中。Node.js 支持四种类型的流:Readable、Writable、Duplex 和 Transform。
const fs = require('fs');const zlib = require('zlib');
// 从文件读取、压缩并写入const readStream = fs.createReadStream('input.txt');const writeStream = fs.createWriteStream('output.txt.gz');const gzip = zlib.createGzip();
readStream.pipe(gzip).pipe(writeStream);5. crypto 模块 (加密)
crypto 模块提供了哈希、加密和随机数生成的功能。
const crypto = require('crypto');
// 密码哈希const hash = crypto.createHash('sha256').update('myPassword123').digest('hex');console.log(hash);
// 生成随机字节crypto.randomBytes(16, (err, buffer) => { console.log(buffer.toString('hex'));});6. events 模块 (事件)
Node.js 中的许多对象(例如流、服务器)都继承自 EventEmitter。该模块允许创建自定义事件。