当前位置: 首页 > news >正文

【前后端】Node.js 模块大全

用到的全部总结在这里,不定期更新

  • 链接
    node一本通
    包括:
    express
    path
    fs/
    process/
    os/
    http/
    mysql/mongoose/
    express-jwt/jsonwebtoken/
    dotenv/
    multer/
    swagger/
    cors/
    nodemon (docker篇有)
  • 常用模块
    • 内置
      fs 文件系统操作(读写、重命名等)
      path 路径处理(拼接、解析、扩展名等)
      http 创建 HTTP 服务或客户端
      os 获取操作系统信息(CPU、内存等)
      events 事件驱动机制(监听、触发事件).
      stream 处理流式数据(文件读写、管道等).
      crypto 加密、哈希、签名等安全相关功能.
      child_process 创建子进程、执行命令行任务.
      util 工具函数(继承、promisify 等).
    • 第三方:
      express Web 框架,快速构建 API 服务
      axios 发起 HTTP 请求(支持 Promise)
      dotenv 加载 .env 环境变量配置
      chalk 终端输出彩色文本
      commander 构建命令行工具
      nodemon 自动重启 Node 服务(开发利器)
      jsonwebtoken JWT 鉴权与令牌生成
      mongoose MongoDB ODM,操作数据库更方便
      cors 处理跨域请求
      body-parser 解析请求体(Express 中常用).
      multer 处理文件上传
      socket.io 实现 WebSocket 实时通信

目录

  • URL / URLSearchParams/ qs
  • axios 发起 HTTP 请求(支持 Promise)
  • body-parser 解析请求体(Express 中常用)
  • commander
  • chokidar
  • open
  • chalk
  • socket.io
  • 插件机制

URL / URLSearchParams/ qs

URL / URLSearchParams 是node/浏览器都支持
qs 第三方库,用于处理复杂query(嵌套对象/数组),放入浏览器需要打包(webpack/vite)npm i qs

const myURL = new URL('https://example.com:8080/path?a=123&b=456#hash')
console.log(myURL.protocol)  // 'https:'
console.log(myURL.hostname)  // 'example.com'
console.log(myURL.port)      // '8080'
console.log(myURL.pathname)  // '/path'
console.log(myURL.hash)      // '#hash'
console.log(url.search);     // '?a=123&b=456'const params = url.searchParams;//得到URLSearchParams 实例对象// 操作 query 参数
myURL.searchParams.set('a', '100')
console.log(myURL.toString()) // https://example.com:8080/path?a=100&b=2#hash// 遍历 query 参数
for (const [key, value] of myURL.searchParams) {console.log(key, value)
}//正则表达式这种 实际上并不是URL底层原理,因为它覆盖不全、边界出错、可读性差、效率低
const url = 'http://www.example.com/a/index.html?a=123&b=456';
const regex = /^(https?):\/\/([^\/?#]+)(\/[^?#]*)?(\?[^#]*)?(#.*)?$/;//URLSearchParams
//空值和无值的参数都会被解析为 ''
const params = new URLSearchParams('?name=Alice&age=30');
console.log(params.get('name'));      // "Alice" 
//还有getAll
console.log(params.has('age'));       // true
params.set('age', '31');              // 修改 age 参数
params.append('hobby', 'reading');    // 添加 hobby 参数
console.log(params.toString());       // "name=Alice&age=31&hobby=reading"
/*
.delete(key)	删除指定参数
.sort()	按参数名排序
.entries()	获取所有键值对迭代器
.keys() / .values()	获取所有键或值的迭代器
.forEach()	遍历所有参数
*///qs
const qs = require('qs')
// 对象 → query 字符串
const str = qs.stringify({a: 1,b: [2, 3],c: { d: 4 }
})
console.log(str)
// a=1&b[0]=2&b[1]=3&c[d]=4
// 字符串 → 对象
const obj = qs.parse('a=1&b[0]=2&b[1]=3&c[d]=4')
console.log(obj)
// { a: '1', b: ['2', '3'], c: { d: '4' } }// URL: /search?filter[status]=active&filter[tags][]=js&filter[tags][]=vue
app.get('/search', (req, res) => {// 默认 Express 不支持嵌套解析,需要 qs 手动解析const filter = require('qs').parse(req.query)console.log(filter)
})

axios 发起 HTTP 请求(支持 Promise)

在nodejs 和 js 用法基本一样,但有细节差异

项目浏览器环境Node.js 环境
请求底层使用 XMLHttpRequestfetch使用 Node 的 httphttps 模块
Cookie 自动携带默认携带当前域名下的 Cookie需要手动设置 withCredentialsheaders
CORS 跨域限制受浏览器安全策略限制不受限制,可自由请求任何地址
文件上传使用 FormData需使用 form-data 模块或 Buffer
浏览器特性支持可显示加载动画、进度条等需手动实现进度监听逻辑
  • 应用场景
    调用第三方 API:比如天气、支付、地图、AI 接口等
    服务间通信:微服务架构中,一个服务调用另一个服务的接口
    数据同步:定时任务拉取远程数据,写入数据库
    代理转发请求:结合 Express 做 API 网关或中间层
    上传/下载文件:配合 fs 模块处理文件流
    自动化脚本:比如爬虫、批量提交数据、接口测试等
//对比 上JS 下node
import axios from 'axios';
axios.get('/api/user').then(res => console.log(res.data)).catch(err => console.error(err));const axios = require('axios');
axios.get('https://api.example.com/user').then(res => console.log(res.data)).catch(err => console.error(err));axios.get('https://api.example.com/data', {withCredentials: true // 允许携带跨域 Cookie
});axios.get('https://api.example.com/data', {headers: {Cookie: 'sessionId=abc123' // 手动设置 Cookie}
});const formData = new FormData();
formData.append('file', fileInput.files[0]);
axios.post('/upload', formData, {headers: { 'Content-Type': 'multipart/form-data' }
});const FormData = require('form-data');
const fs = require('fs');
const formData = new FormData();
formData.append('file', fs.createReadStream('./file.jpg'));
axios.post('https://api.example.com/upload', formData, {headers: formData.getHeaders()
});axios.get('/bigfile', {onDownloadProgress: progressEvent => {console.log(`下载进度: ${progressEvent.loaded} 字节`);}
});axios.get('https://example.com/bigfile', { responseType: 'stream' }).then(response => {let total = 0;response.data.on('data', chunk => {total += chunk.length;console.log(`下载进度: ${total} 字节`);});});

body-parser 解析请求体(Express 中常用)

  • 作用:在 Express 中,默认 无法读取 req.body,需要 body-parser 这个中间件来解析
  • 安装npm i ...
    更新:Express 4.16+ 内置了替代方案!从 Express 4.16 起,可以不用单独装 body-parser,直接使用即可,把bodyParser改为express
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
  • 使用
app.post('/login', (req, res) => {console.log(req.body) // ❌ 默认是 undefined
})const express = require('express')
const bodyParser = require('body-parser')const app = express()// 解析 application/json 类型的请求体
app.use(bodyParser.json())// 解析 application/x-www-form-urlencoded(表单)类型
app.use(bodyParser.urlencoded({ extended: true }))
//统一就写死成true app.post('/login', (req, res) => {console.log(req.body) // ✅ 正常打印对象res.send('登录成功')
})

commander

npm install commander
  • 作用
    命令行工具构建库
    定义命令行命令(如:init、build)
    解析参数(如:–force、-o output)
    自动生成 --help 帮助文档
    监听不同命令的回调函数
  • 使用
// cli.js
const { Command } = require('commander')
const program = new Command()program.name('mycli').description('一个自定义 CLI 工具').version('1.0.0')// 定义命令 mycli init
program.command('init').description('初始化项目').option('-f, --force', '是否强制初始化').action((options) => {require('./commands/init')(options)console.log('初始化项目,参数:', options)})// 解析命令行参数
program.parse(process.argv)//多个命令
program.command('build').description('构建项目').option('-o, --output <path>', '输出路径', './dist').action((options) => {require('./commands/build')(options)console.log('构建项目,输出到:', options.output)})// export 命令
program.command('export').description('导出 HTML').option('-t, --theme <name>', '使用的主题').action((options) => {require('./commands/export')(options)})program.parse()//默认命令
program.action(() => {console.log('你没有输入命令,显示帮助:')program.help()})
//帮助信息自动生成,不需要手动写//支持传参
program.command('add <name>').description('添加一个组件').action((name) => {console.log('添加组件:', name)}).command('export [file]')
.action((file, options) => {// file 是导出的文件名
})//package.json中要配置好
"bin": {"mycli": "./cli.js"
}
  • 应用:Webpack 和 Vite 本质上就是 CLI(命令行工具),但它们远不止于此——它们不仅是命令行工具,更是构建工具、模块打包器、开发服务器、插件平台、模块解析与优化 、编译器集成。

chokidar

  • 作用
    高效、跨平台的 文件监听库,基于底层 fs.watch 和 fs.watchFile,但做了大量兼容性增强和性能优化。
  • 使用
事件名触发时机
add文件被新增
addDir文件夹被新增
change文件内容发生变化
unlink文件被删除
unlinkDir文件夹被删除
ready初始扫描完成
error出现错误
const chokidar = require('chokidar')// 初始化监听器,监听某个文件或目录
const watcher = chokidar.watch('src/**/*.md', {ignored: /(^|[\/\\])\../, // 忽略隐藏文件//.开头的隐藏文件 或者是文件夹里面的.开头的隐藏文件persistent: true
})// 监听事件
watcher.on('add', path => console.log(`📄 新增文件: ${path}`)).on('change', path => console.log(`✏️  文件变动: ${path}`)).on('unlink', path => console.log(`❌ 删除文件: ${path}`))const watcher = chokidar.watch('src', {ignored: /node_modules/,persistent: true,//持续在后台运行 不自动退出ignoreInitial: false,     // 是否忽略第一次加载时触发的 add 事件usePolling: false,        // 如果 true,强制使用轮询(性能较差,兼容某些平台)interval: 100,            // 轮询间隔(仅当 usePolling 为 true)awaitWriteFinish: {stabilityThreshold: 200,//多久没有变化就认为写入完成pollInterval: 100 //检测写入变化的频率}
})watcher.on('change', (path) => {const content = fs.readFileSync(path, 'utf-8')socket.emit('update', content) // 配合 socket.io 实现热更新
})
watcher.on('change', (filePath) => {const html = render(fs.readFileSync(filePath, 'utf-8'))io.emit('reload', html)
})//自动重新构建
watcher.on('change', (filePath) => {build(filePath)
})

open

  • 版本
    open@10+ 默认导出是 ESM(export default),你用 require() 会报错,如果你用的是 type: “module” 或 .mjs,直接 import chalk from 'chalk'
    如果项目是 CommonJS,可以使用 open@9
  • 作用
    Node.js 第三方库,可以帮你 在默认程序中打开 URL、文件、目录、应用程序等。open 会自动判断当前平台(Windows/macOS/Linux)来选择合适的系统调用,无需你手动处理跨平台问题。
    常用于 CLI 工具中,比如 vite 启动后自动打开浏览器:就是用 open(‘http://localhost:3000’) 实现的。
  • 使用
打开类型示例
打开网页open('https://google.com')
打开本地文件open('README.md')
打开本地目录open('.')
打开应用程序open('https://google.com', { app: 'firefox' })
选项作用
app.name指定打开的应用名(如 chrome, firefox, code, sublime
app.arguments传给应用的参数(如打开无痕、指定窗口等)
wait是否等待程序退出(默认 false
newInstance是否强制新开一个程序实例
import open from 'open'// 在默认浏览器中打开 URL
await open('https://example.com')
// 打开项目目录
await open('./my-project')
// 打开 Markdown 文件(默认编辑器或预览)
await open('./README.md')const open = require('open')
open('https://example.com')// 打开 VSCode
await open('.', { app: { name: 'code' } })// 打开 Chrome 并传参
await open('https://example.com', {app: {name: 'google chrome',arguments: ['--new-window']}
})

chalk

  • 版本
    从 v5 起,chalk 是 ESM-only(只能用 import),如果你项目是 CommonJS,推荐使用 v4 npm install chalk@4
  • 作用:给 命令行文本添加颜色和样式
  • 使用
// ESM 写法(v5+)
import chalk from 'chalk'// 输出彩色文字
console.log(chalk.green('成功!'))
console.log(chalk.red('错误!'))
console.log(chalk.yellow('警告!'))
console.log(chalk.blue('信息'))
//链式调用
console.log(chalk.bold.red('加粗红色'))
console.log(chalk.bgYellow.black('黑字黄底'))
console.log(chalk.underline.green('下划线绿色'))//变量定义 封装success/error/info
const error = chalk.bold.red
const warning = chalk.hex('#FFA500') // 自定义颜色(橙色)
console.log(error('出错了!'))
console.log(warning('警告:请检查配置文件'))const log = console.log
log(chalk.bold.green('✔ 操作成功'))
log(chalk.bold.yellow('⚠ 请检查配置'))
log(chalk.bold.red('✖ 出现错误'))
log.success('成功')
log.error('失败')
log.info('提示')//模版字符串嵌入颜色
console.log(`这是一个 ${chalk.green('成功')} 的例子`)

socket.io

  • 作用
    Node.js 实时通信库,基于 WebSocket 封装,提供客户端-服务端之间的全双工通信能力,支持自动重连、断线重试、事件通信等。
  • 应用:实时聊天、实时数据推送(如股票/价格更新)、热更新、多人协同编辑

插件机制

  • 作用:支持用户自定义
  • 核心思路
    “插件机制” = 约定接口 + 自动调用
    只需要:
    允许用户传入插件(数组)
    在渲染时循环调用这些插件(钩子)
    插件只要满足某些方法签名就能工作
  • 定义插件格式
//sample_plugin.js
module.exports = {name: 'my-plugin',// 在渲染前调用,可修改原始内容beforeRender(content, options) {return content},// 渲染为 HTML 后调用,可修改 HTML 字符串afterRender(html, options) {return html}
}
//example
// plugins/copyright-plugin.jsmodule.exports = {name: 'copyright-plugin',afterRender(html) {return html + `<footer><p style="text-align:center;color:#aaa;">© hello 2025 </p></footer>`}
}
  • 修改执行文件来支持插件机制,引入插件加载器.js,用它加载所有插件,循环分别在渲染前/渲染后执行对应函数即beforeRender/afterRender
const fs = require('fs')
const path = require('path')
const loadPlugins = require('./plugins')function operator(filePath, theme = 'default', pluginPaths = []) {let Content = fs.readFileSync(filePath, 'utf-8')// 加载插件const plugins = loadPlugins(pluginPaths)// 插件处理原始内容for (const plugin of plugins) {if (plugin.beforeRender) {Content = plugin.beforeRender(Content, { theme })}}const renderer = new xx()let NewContent = renderer.render(Content)// 插件处理 HTML 内容for (const plugin of plugins) {if (plugin.afterRender) {NewContent = plugin.afterRender(NewContent, { theme })}}const cssPath = `/styles/${theme}.css`return `
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8" /><title>Preview</title><link rel="stylesheet" href="${cssPath}">
</head>
<body><div class="content">${NewContent}</div>
</body>
</html>`
}module.exports = operator
  • 创建插件加载器
//loader.js
const path = require('path')
const fs = require('fs')function loadPlugins(pluginPaths) {const plugins = []for (const pluginPath of pluginPaths) {const abs = path.resolve(process.cwd(), pluginPath)if (fs.existsSync(abs)) {const plugin = require(abs)plugins.push(plugin)} else {console.warn(`⚠️ 插件 ${pluginPath} 不存在`)}}return plugins
}module.exports = loadPlugins
  • 支持命令行传插件
//修改CLI支持--plugin参数 可多次
.option('--plugin <path...>', '加载插件')//...是commander里的rest参数 
  • 插件注册 API 提供 use() 方法,内部注册插件
    方法封装成类
//lib/pluginManager.js
const fs = require('fs')
const path = require('path')class PluginManager {constructor() {this.plugins = []}// 注册插件use(plugin) {if (typeof plugin === 'object') {this.plugins.push(plugin)} else {console.warn(`插件无效:${plugin}`)}return this // 支持链式调用}// 渲染流程,内部挂载插件钩子render(filePath, theme = 'default') {//封装beforeRender->render->afterRenderconst cssPath = `/styles/${theme}.css`return `
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8" /><title>Preview</title><link rel="stylesheet" href="${cssPath}">
</head>
<body><div class="content">${htmlContent}</div>
</body>
</html>`}
}module.exports = new PluginManager()//使用
const pluginManager = require('./pluginManager')
// 注册插件
pluginManager.use(require('./plugins/copyright-plugin')).use(require('./plugins/toc-plugin'))
// 渲染
const html = pluginManager.render(filePath, theme)//复用
const pluginManager = require('../lib/pluginManager')
// 注册所有传入的插件
if (options.plugin && options.plugin.length) {for (const pluginPath of options.plugin) {const abs = path.resolve(process.cwd(), pluginPath)const plugin = require(abs)pluginManager.use(plugin)}
}
if (options.export) {//导出渲染const html = pluginManager.render(filePath, options.theme)fs.writeFileSync(options.export, html)
} else {// 启动服务器时也用 pluginManager.render()
}
  • 插件系统生命周期钩子 init、beforeRender、afterRender、onError
    Node.js 本身并没有统一的“插件生命周期钩子”机制,不像 Webpack、Fastify、Nuxt 等框架那样提供标准化的钩子系统。但在 Node.js 的生态中,很多框架和工具都实现了自己的插件机制和生命周期钩子。
    把这些插件自带的钩子都补进 pluginManager.render() 中,非常好扩展。
生命周期钩子名触发时机是否异步支持
init(options)插件初始化时支持
beforeRender(content, options)渲染前支持
afterRender(html, options)渲染后支持
onError(err)渲染出错时支持
onFinish()渲染流程结束支持
  use(plugin) {if (plugin && typeof plugin === 'object') {// 调用 init 钩子if (typeof plugin.init === 'function') {try {plugin.init()} catch (e) {console.warn(`插件 ${plugin.name} 初始化失败:`, e)}}this.plugins.push(plugin)}return this}catch (err) {console.error(`❌ 渲染失败: ${err.message}`)// 错误钩子for (const plugin of this.plugins) {if (typeof plugin.onError === 'function') {try {plugin.onError(err)} catch (e) {console.warn(`插件 ${plugin.name} onError 失败:`, e)}}}}// 渲染完成钩子for (const plugin of this.plugins) {if (typeof plugin.onFinish === 'function') {try {plugin.onFinish()} catch (e) {console.warn(`插件 ${plugin.name} onFinish 失败:`, e)}}}
//....
module.exports = new PluginManager()// plugins/dev-logger.js
module.exports = {name: 'dev-logger',init() {console.log('[dev-logger] 插件已加载')},beforeRender(content) {console.log('[dev-logger] 渲染前内容长度:', content.length)return content},afterRender(html) {console.log('[dev-logger] 渲染后 HTML 长度:', html.length)return html},onError(err) {console.error('[dev-logger] 渲染异常:', err)},onFinish() {console.log('[dev-logger] 渲染流程完成 🎉')}
}
  • 插件默认目录 自动加载 ./plugins/*.js
    封装自动加载逻辑
//lib/loadLocalPlugins.jsconst path = require('path')
const fs = require('fs')function loadLocalPlugins() {const pluginsDir = path.resolve(process.cwd(), 'plugins')const pluginList = []if (!fs.existsSync(pluginsDir)) return []const files = fs.readdirSync(pluginsDir)for (const file of files) {const ext = path.extname(file)if (ext === '.js') {const fullPath = path.join(pluginsDir, file)try {const plugin = require(fullPath)pluginList.push(plugin)} catch (e) {console.warn(`⚠️ 插件加载失败:${file}`, e)}}}return pluginList
}module.exports = loadLocalPlugins//控制加载顺序
//在插件文件中加一个 order 字段
module.exports = {name: 'copyright',order: 10,afterRender(html) {return html + '<footer>© 2025</footer>'}
}
//loadLocalPlugins里排序
pluginList.sort((a, b) => (a.order || 0) - (b.order || 0))

搭配上之前的手动传参,实现自动手动一起加载

  • 插件配置文件 支持读取 .previewrc 配置文件加载插件
    让用户通过项目根目录的 .previewrc 文件自动配置插件和主题,避免复杂命令行参数。
//支持JSON格式
{"theme": "hacker","plugins": ["./plugins/copyright-plugin.js","./plugins/toc-plugin.js"]
}
//配置读取模块 lib/loadConfig.jsconst fs = require('fs')
const path = require('path')function loadConfig() {const configPath = path.resolve(process.cwd(), '.previewrc')if (!fs.existsSync(configPath)) return {}try {const raw = fs.readFileSync(configPath, 'utf-8')const config = JSON.parse(raw)return config} catch (e) {console.warn('⚠️ 配置文件 .previewrc 加载失败:', e.message)return {}}
}module.exports = loadConfig//调用加载配置并合并参数
// 加载 .previewrc
const rc = loadConfig()// 合并 theme 设置(命令行优先生效)
const theme = options.theme || rc.theme || 'default'// 加载插件(来自 CLI 参数 + .previewrc + plugins/ 目录)
const allPlugins = [...(rc.plugins || []),...(options.plugin || [])
]

文章转载自:
http://acculturation.apjjykv.cn
http://butylate.apjjykv.cn
http://chorology.apjjykv.cn
http://celtuce.apjjykv.cn
http://apropos.apjjykv.cn
http://beanstalk.apjjykv.cn
http://annuli.apjjykv.cn
http://carpospore.apjjykv.cn
http://centile.apjjykv.cn
http://analyzing.apjjykv.cn
http://catamite.apjjykv.cn
http://choreography.apjjykv.cn
http://almswoman.apjjykv.cn
http://appropriable.apjjykv.cn
http://araroba.apjjykv.cn
http://asshur.apjjykv.cn
http://chasmophyte.apjjykv.cn
http://andorran.apjjykv.cn
http://aubade.apjjykv.cn
http://ambivalence.apjjykv.cn
http://armpad.apjjykv.cn
http://cantorial.apjjykv.cn
http://awkward.apjjykv.cn
http://chinchilla.apjjykv.cn
http://chapelry.apjjykv.cn
http://algol.apjjykv.cn
http://browny.apjjykv.cn
http://ampholyte.apjjykv.cn
http://adiposis.apjjykv.cn
http://addict.apjjykv.cn
http://www.dtcms.com/a/281133.html

相关文章:

  • 巨坑检查无误还报错is not mapped MappingException: Unknown entity:@Entity
  • DeepSWE:通过强化学习扩展训练开源编码智能体
  • 多层 `while` 循环中,`break` 的行为
  • ES2023 新特性解析_数组与对象的现代化操作指南
  • 二分查找栈堆
  • 【C语言进阶】字符函数和字符串函数的内部原理
  • “ModuleNotFoundError“深度解析:Python模块导入问题的终极指南
  • PHP语言基础知识(超详细)第二节
  • OSPFv3中LSA参数
  • dbever 导出数据库表的建表语句和数据插入语句
  • 嵌入式Linux:进程间通信机制
  • AJAX 开发中的注意点
  • ASRPRO系列语音模块(第十天)
  • AI 增强大前端数据加密与隐私保护:技术实现与合规遵
  • Python 程序设计讲义(2):Python 概述
  • pc浏览器页面语音播报功能
  • 多路文件IO的几个模型
  • K-means 聚类在肺炎患者分型中的应用(简单示例)
  • 轻轻松松带你进行-负载均衡LVS实战
  • 随机奖励能提升Qwen数学表现?本质是数据污染
  • brupsuite使用中遇到的一些问题(bp启动后浏览器无法连接)/如何导入证书
  • YCQ340汽油机气缸体总成设计cad【8张】设计说明书
  • 模拟C++简易配置系统(模板类 + 全局管理)
  • 一区 Top (HPJ) | WGAS+WGCNA分析文章套路
  • 零基础学软件测试:超详细软件测试基础理论知识讲解
  • 【实时Linux实战系列】使用系统调用实现实时同步
  • Java项目:基于SSM框架实现的学生档案管理系统【ssm+B/S架构+源码+数据库+毕业论文+开题报告】
  • 智能体技术深度解析:从概念到企业级搭建指南
  • 自学java,什么书比较好?
  • MaxKB使用笔记【持续ing】