第三章:Node.js核心模块
3.1 全局对象
// __filename - 当前文件路径
console.log(__filename);
// __dirname - 当前目录路径
console.log(__dirname);
// process - 进程信息
console.log(process.version);
console.log(process.env);
// Buffer - 二进制数据
const buf = Buffer.from('Hello');
console.log(buf.toString());
3.2 path模块
const path = require('path');
// 路径拼接
const fullPath = path.join('/home', 'user', 'file.txt');
console.log(fullPath);
// 获取目录名
console.log(path.dirname('/home/user/file.txt'));
// 获取文件名
console.log(path.basename('/home/user/file.txt'));
// 获取扩展名
console.log(path.extname('/home/user/file.txt'));
// 解析路径
const parsed = path.parse('/home/user/file.txt');
console.log(parsed);
// 判断绝对路径
console.log(path.isAbsolute('/home/file.txt'));
3.3 os模块
const os = require('os');
console.log(os.platform());
console.log(os.hostname());
console.log(os.totalmem());
console.log(os.freemem());
console.log(os.cpus().length);
console.log(os.homedir());
console.log(os.tmpdir());
3.4 url模块
const url = require('url');
const myURL = new URL('https://example.com:8080/path?name=value');
console.log(myURL.protocol);
console.log(myURL.hostname);
console.log(myURL.pathname);
console.log(myURL.searchParams.get('name'));
3.5 querystring模块
const querystring = require('querystring');
// 解析
const parsed = querystring.parse('name=张三&age=25');
console.log(parsed);
// 序列化
const str = querystring.stringify({ name: '张三', age: 25 });
console.log(str);
3.6 events模块
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
// 监听事件
myEmitter.on('event', (data) => {
console.log('事件触发:', data);
});
// 触发事件
myEmitter.emit('event', { message: 'Hello' });
// 一次性监听
myEmitter.once('once', () => {
console.log('只执行一次');
});
3.7 util模块
const util = require('util');
const fs = require('fs');
// 格式化
console.log(util.format('%s:%d', 'foo', 25));
// 回调转Promise
const readFile = util.promisify(fs.readFile);
// 检查类型
console.log(util.isArray([1, 2, 3]));
// 对象检查
console.log(util.inspect({ a: 1, b: 2 }));
3.8 crypto模块
const crypto = require('crypto');
// MD5哈希
const md5 = crypto.createHash('md5')
.update('Hello')
.digest('hex');
// SHA256哈希
const sha256 = crypto.createHash('sha256')
.update('Hello')
.digest('hex');
// 随机字节
const randomBytes = crypto.randomBytes(16).toString('hex');
// 对称加密
const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update('Hello', 'utf8', 'hex');
encrypted += cipher.final('hex');
const decipher = crypto.createDecipheriv(algorithm, key, iv);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');