一、path 路径处理
1. join
将多个路径拼接成一个相对路径 (或绝对路径,取决于第一个路径是否为根路径)
import path from 'path'
console.log(path.join('a', 'b')) // a/b
console.log(path.join('/a', '/b', './c')) // /a/b/c
console.log(path.join('/a', '/b', '../c')) // /a/c
2. resolve
将多个路径拼接成一个绝对路径,返回一个解析后的绝对路径。 如果传入相对路径,会以当前工作目录为基准,计算出绝对路径;如果传入了绝对路径,则以传入的绝对路径为基准。
console.log(path.resolve('a', 'b')) // 以当前工作目录为基准计算绝对路径
console.log(path.resolve('/a', '/b', './c')) // /b/c 以传入的绝对路径为基准拼接
console.log(path.resolve('/a', '/b', '../c')) // /c
console.log(path.resolve('/a', 'b')) // /a/b
3. dirname
返回路径的目录名
4. basename(filepath, [ext])
返回路径中的文件名,并可选地去除给定的文件扩展名
path.basename('./a/name.js') // name.js
path.basename('./a/name.js', '.js') // name
5. extname: 获取文件扩展名
6. normalize
规范化路径;会处理斜杠数量过多、相对路径的情况
path.normalize('a/b/c/../../d') // -> a/d
path.normalize('../a/b///c/d') // -> ../a/b/c/d
7. parse
将路径字符串解析为对象,返回一个对象,包含以下属性:
- root: 路径的根目录
- dir: 路径中的目录部分
- base: 路径中的文件名部分
- ext: 文件扩展名
- name: 文件名,不包含扩展名
二、url模块
1.url.parse: 解析url,返回一个解析后的对象
import url from 'url';
const parsedObj = url.parse('http://test.com/a/b/c?name=test&key=a#1');
2. URL: 与全局URL一样,可用于创建URL实例
const testUrl = 'https://www.baidu.com?search=juejin'
console.log('url.URL === URL', url.URL === URL) // true
// 可以通过 searchParams 获取查询信息
console.log(testUrl.searchParams.get('search')) // juejin
三、util模块
提供了一些工具方法,比如格式化字符串、类型检测方法等
1. format
支持占位符(%s %d %j %f %i等)表示不同的变量,支持传入多个参数
import util from 'util'
util.format('%d + %d = %d', 2, 2, 4) // 2 + 2 = 4
util.format('%s %d %j', 'a', 1, { a: 1 }); // a 1 {"a": 1}
util.format('%f %i', 0.1, 2.6) // 0.1 2
2.inspect
常与console.log一起使用,可以更好的将对象转换成字符串,打印更加友好
// 复杂对象
const testObj = {
a: 1,
b: {
c: 2,
d: [3, 4, 5],
e: () => {
console.log(6)
}
},
f: [{ 8: [{ 9: 10 }] }],
}
console.log(testObj)
// depth 用于控制展开的层级
console.log(util.inspect(testObj, { depth: Infinity }));
3. callbackify
将一个返回promise的函数转换成回调形式
function promiseFn() {
return Math.random() > 0.5 ? Promise.resolve('success') : Promise.reject('error');
}
const callbackFn = util.callbackify(promiseFn);
callbackFn((err, ret) => {
if (err) throw err;
console.log('ret', ret);
});
4.promisify
将回调形式转换成promise
const readFilePromise = util.promisify(fs.readFile);
const res = await readFilePromise('./index.js');
console.log('res', res.length)
5.types
types下有很多方法可以用于类型检测
console.log(util.types.isDate(new Date())) // true
console.log(util.types.isRegExp(/a/)) // true
const asyncFn = async () => {}
console.log(util.types.isAsyncFunction(asyncFn)) // true
console.log(util.types.isPromise(Promise.resolve())) // true
console.log(util.types.isGeneratorFunction(function* () {})) // true
四、crypto 模块
crypto模块主要用于加密和解密数据,内置了一些常用的算法
1. 哈希值生成
import crypto from 'crypto';
// 1. 创建一个新的哈希算法实例 crypto.createHash(algorithm)
const hashInstance = crypto.createHash('sha256');
// 2. 更新哈希运算所使用的数据
hashInstance.update('hello');
// 3. 计算并返回哈希值
const sha256 = hashInstance.digest('hex');
const md5 = crypto.createHash('md5').update('hello').digest('hex');
console.log('md5', md5)
2.加解密
// 定义加密算法和密钥,生成随机密码和向量
const algorithm = 'aes-256-cbc'
const password = crypto.randomBytes(32) // 生成随机 32 字节的密码
const iv = crypto.randomBytes(16) // 生成随机 16 字节的向量
// 待加密的数据
const data = 'Hello, World!'
console.log('Original data:', data)
// 创建加密算法实例
const cipher = crypto.createCipheriv(algorithm, password, iv)
// 使用 update 方法对数据进行加密
let encrypted = cipher.update(data, 'utf8', 'hex')
console.log('encrypted', encrypted)
// 加密后的数据以十六进制形式(即字符串)返回
encrypted += cipher.final('hex')
console.log('Encrypted data:', encrypted)
// 创建解密算法实例
const decipher = crypto.createDecipheriv(algorithm, password, iv)
// 使用 update 方法对数据进行解密
let decrypted = decipher.update(encrypted, 'hex', 'utf8')
// 返回解密后的字符串 utf8编码
decrypted += decipher.final('utf8')
console.log('Decrypted data:', decrypted)
五、os 模块
os 模块用于获取操作系统的相关信息
console.log('系统的CPU架构信息', os.arch());
console.log('系统平台信息', os.platform());
console.log('CPU内核的信息', os.cpus())
console.log('系统总内存量', os.totalmem())
console.log('空闲内存量', os.freemem())
console.log('系统主机名', os.hostname())
console.log('系统网络信息', os.networkInterfaces())