🟢 Node.js 完整笔记
Node.js 笔记
目录
Node.js 简介
Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行时环境,允许在服务器端执行 JavaScript 代码。
特点:
- 事件驱动、非阻塞 I/O 模型
- 轻量高效,适合数据密集型实时应用
- npm 是全球最大的开源库生态系统
版本说明:
- LTS (Long Term Support):长期稳定版,推荐生产环境使用
- Current:最新特性版,包含最新功能但可能不稳定
安装 Node.js
Windows 系统
方式一:官网下载安装包
- 访问 Node.js 官网
- 下载 Windows Installer (.msi)
- 运行安装程序,一路 Next 即可
方式二:使用 Chocolatey
# 安装 Chocolatey (需管理员权限)iwr https://chocolatey.org/install.ps1 -UseBasicParsing | iex
# 安装 Node.jschoco install nodejs方式三:使用 Winget
winget install OpenJS.NodeJSwinget install OpenJS.NodeJS.LTSmacOS 系统
方式一:官网下载安装包
- 访问 Node.js 官网
- 下载 macOS Installer (.pkg)
- 运行安装程序
方式二:使用 Homebrew
# 安装 Homebrew (若未安装)/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# 安装 Node.jsbrew install node
# 安装 LTS 版本brew install node@lts方式三:使用 nvm
# 安装 nvm (见下文 nvm 章节)Linux 系统
Ubuntu / Debian
# 更新系统包sudo apt updatesudo apt upgrade
# 移除旧版本(若有)sudo apt remove nodejs npm
# 添加 NodeSource 仓库 (以 LTS 版本为例)curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
# 安装 Node.jssudo apt-get install -y nodejs
# 验证安装node -vnpm -vCentOS / RHEL / Fedora
# 添加 NodeSource 仓库curl -fsSL https://rpm.nodesource.com/setup_lts.x | sudo bash -
# 安装 Node.jssudo yum install -y nodejs
# 或使用 dnfsudo dnf install -y nodejsArch Linux
sudo pacman -S nodejs npmAlpine Linux
apk add nodejs npmDocker 环境中使用
# 拉取官方镜像docker pull node:latestdocker pull node:lts
# 运行交互式容器docker run -it node:latest bash
# 运行特定版本docker run -it node:18 bash版本管理工具 nvm
nvm (Node Version Manager) 允许在同一台机器上管理多个 Node.js 版本。
安装 nvm
Linux / macOS
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash或使用 wget:
wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bashWindows Windows 系统使用 nvm-windows:
- 下载安装包:https://github.com/coreybutler/nvm-windows/releases
- 运行安装程序
nvm 常用命令
# 安装 nvm-windows 后验证nvm version
# 查看可用版本nvm list available
# 安装最新稳定版nvm install ltsnvm install --lts
# 安装最新版本nvm install latest
# 安装指定版本nvm install 18.17.0nvm install 20
# 查看已安装版本nvm listnvm ls
# 切换使用某个版本nvm use 18.17.0nvm use lts
# 设置默认版本nvm alias default 18.17.0
# 卸载指定版本nvm uninstall 16.20.0
# 查看当前版本nvm current
# 允许在特定版本上运行命令nvm run 18.17.0 --versionnvm 高级配置
# 设置镜像 (解决国内下载慢的问题)export NVM_NODEJS_ORG_MIRROR=https://npmmirror.com/mirrors/node
# 开启/关闭 node 版本自动切换echo 'autoload -U add-zsh-hook' >> ~/.zshrcload-nvmrc() { ... } # 可配置自动读取 .nvmrc 文件包管理器
npm (Node Package Manager)
npm 是 Node.js 默认的包管理器,集成在 Node.js 安装包中。
pnpm (Performant npm)
pnpm 是一个快速、节省空间的包管理器,使用硬链接避免重复存储。
安装 pnpm
# 使用 npm 安装npm install -g pnpm
# 使用 corepack 启用 (Node.js 16+)corepack enablecorepack prepare pnpm@latest --activate
# 使用脚本安装curl -fsSL https://get.pnpm.io/install.sh | sh -pnpm 常用命令
pnpm installpnpm add <package>pnpm add <package> -D # 开发依赖pnpm add <package> -g # 全局安装pnpm remove <package>pnpm updatepnpm outdatedpnpm listpnpm list -gpnpm run <script>pnpm inityarn
安装 yarn
# 使用 npm 安装npm install -g yarn
# 使用 corepack 启用corepack enablecorepack prepare yarn@stable --activateyarn 常用命令
yarn installyarn add <package>yarn add <package> --devyarn add <package> -gyarn remove <package>yarn upgradeyarn upgrade-interactiveyarn listyarn run <script>yarn inityarn info <package>npm 常用命令
基础命令
# 查看 npm 版本npm -vnpm --version
# 查看帮助npm helpnpm --help
# 查看命令列表npm commandspackage.json 相关
# 初始化项目 (创建 package.json)npm initnpm init -y # 跳过问答,全部默认npm init --yes
# 设置初始值npm init --scope=username # 设置 scope 用户名npm init --yes --scope=username --author-name="Your Name"安装依赖
# 安装项目所有依赖npm installnpm install --legacy-peer-deps # 忽略 peer dependencies 冲突
# 安装指定包npm install <package>npm install <package>@<version> # 指定版本npm install <package>@latest # 最新版本npm install <package>@">=1.0.0 <2.0.0" # 版本范围
# 安装并保存到 dependencies (生产依赖)npm install <package> --savenpm install <package> -Snpm install <package> --save-prod
# 安装并保存到 devDependencies (开发依赖)npm install <package> --save-devnpm install <package> -D
# 安装全局包npm install <package> -gnpm install --global <package>
# 从本地安装npm install ./path/to/packagenpm install /path/to/package.tgz
# 安装 Git URLnpm install git://github.com/user/project.gitnpm install git+ssh://git@github.com:user/project.gitnpm install git+https://github.com/user/project.git
# 安装特定 tagnpm install <package>@betanpm install <package>@rc更新依赖
# 查看可更新的包npm outdated
# 更新所有包npm update
# 更新指定包npm update <package>
# 检查包最新版本npm outdated <package>卸载依赖
# 卸载指定包npm uninstall <package>npm remove <package>npm rm <package>
# 卸载并从 package.json 移除npm uninstall <package> --savenpm uninstall <package> -Snpm uninstall <package> --save-devnpm uninstall <package> -D
# 卸载全局包npm uninstall <package> -g运行脚本
# 运行 package.json 中定义的脚本npm run <script>
# 常用预设脚本npm run start # 启动项目npm run dev # 开发模式npm run build # 构建项目npm run test # 运行测试npm run lint # 代码检查npm run format # 代码格式化
# 直接执行 bin 命令npx <command>npx create-react-app my-app包搜索与管理
# 在 npm 仓库搜索包npm search <keyword>npm s <keyword>
# 查看包信息npm view <package>npm v <package>
# 查看特定信息npm view <package> versionnpm view <package> versionsnpm view <package> dependenciesnpm view <package> repository.urlnpm view <package>engines
# 查看包在仓库中的状态npm pack <package> # 下载包的 tarball查看已安装的包
# 查看当前项目依赖树npm listnpm ls
# 查看全局包npm list -gnpm ls -gnpm list -g --depth=0
# 查看包的所有版本npm view <package> versions --json缓存管理
# 查看缓存npm cache lsnpm cache ls <package>
# 清理缓存npm cache cleannpm cache clean --force
# 验证缓存npm cache verifynpm 配置
# 查看配置npm config listnpm config list -l # 查看所有配置npm config get <key>npm config list --json # JSON 格式输出
# 设置配置npm config set <key> <value>npm config set registry https://registry.npmjs.orgnpm config set <key> <value> --location=user # 用户配置npm config set <key> <value> --location=project # 项目配置
# 删除配置npm config delete <key>
# 编辑配置文件npm config editpackage.json 详解
package.json 是 Node.js 项目的核心配置文件。
基本结构
{ "name": "my-project", "version": "1.0.0", "description": "项目描述", "main": "index.js", "scripts": { "start": "node index.js", "dev": "nodemon index.js", "build": "webpack --mode production", "test": "jest", "lint": "eslint ." }, "keywords": ["nodejs", "javascript"], "author": "Your Name <email@example.com>", "license": "MIT", "repository": { "type": "git", "url": "https://github.com/username/project.git" }, "bugs": { "url": "https://github.com/username/project/issues" }, "homepage": "https://github.com/username/project#readme", "dependencies": {}, "devDependencies": {}}字段说明
| 字段 | 说明 | 示例 |
|---|---|---|
name | 项目名称 | "my-project" |
version | 版本号 | "1.0.0" |
description | 项目描述 | "A cool project" |
main | 入口文件 | "src/index.js" |
type | 模块类型 | "module" 或 "commonjs" |
scripts | 命令别名 | {"start": "node index.js"} |
keywords | 关键字 | ["web", "nodejs"] |
author | 作者 | "Name <email>" |
license | 许可证 | "MIT" |
repository | 仓库地址 | {type: "git", url: "..."} |
engines | Node 版本要求 | {"node": ">=16"} |
os | 支持的操作系统 | ["darwin", "linux"] |
cpu | 支持的 CPU 架构 | ["x64", "arm64"] |
dependencies vs devDependencies
dependencies - 生产环境依赖
"dependencies": { "express": "^4.18.2", "axios": "^1.6.0", "dotenv": "^16.3.1"}devDependencies - 开发环境依赖
"devDependencies": { "webpack": "^5.88.0", "jest": "^29.6.0", "eslint": "^8.45.0"}版本号语义化 (SemVer)
major.minor.patch ^ ^ ^ | | +-- patch: 修复 bug,完全向下兼容 | +------- minor: 新功能,向后兼容 +------------- major: 破坏性更新,不向下兼容| 符号 | 含义 | 示例 |
|---|---|---|
^ | 允许 minor 和 patch 更新 | ^1.2.3 → 1.x.x |
~ | 允许 patch 更新 | ~1.2.3 → 1.2.x |
* | 最新版本 | * |
>= | 大于等于 | >=1.0.0 |
1.0.0 - 2.0.0 | 版本范围 | 1.0.0 - 2.0.0 |
latest | 最新标签版本 | latest |
scripts 变量
{ "scripts": { "build": "webpack --progress --config webpack.config.js", "postinstall": "if [ -f ./scripts/postinstall.js ]; then node ./scripts/postinstall.js; fi", "prebuild": "rimraf dist" }}常用生命周期钩子:
preinstall- 安装前postinstall- 安装后preuninstall- 卸载前postuninstall- 卸载后prepublish- 发布前preversion- 版本更新前postversion- 版本更新后pretest/posttest- 测试前后prestop/poststop- 停止前后prestart/poststart- 启动前后
模块系统
CommonJS (CJS)
Node.js 默认的模块系统,使用 require() 导入和 module.exports 导出。
const add = (a, b) => a + b;module.exports = add;
// 导出方式 2: module.exports = {}module.exports = { add, subtract: (a, b) => a - b};
// 导出方式 3: exports.aliasexports.add = add;exports.subtract = (a, b) => a - b;
// 导入const add = require('./math');const { add, subtract } = require('./math');ES Modules (ESM)
ES6 引入的模块系统,使用 import 导入和 export 导出。
注意: 需要在 package.json 中设置 "type": "module",或使用 .mjs 扩展名。
// 导出方式 1: exportexport const add = (a, b) => a + b;export const subtract = (a, b) => a - b;
// 导出方式 2: export defaultconst add = (a, b) => a + b;export default add;
// 导出方式 3: export { }const add = (a, b) => a + b;export { add };
// 导入import add from './math.js';import { add, subtract } from './math.js';import * as math from './math.js';模块解析
// 相对路径require('./utils'); // ./utils.jsrequire('./utils.js'); // 明确扩展名require('./'); // 查找 ./index.js
// 绝对路径require('/usr/local/utils'); // 绝对路径
// 模块路径 (node_modules)require('express'); // 查找 node_modules/expressrequire('@babel/core'); // 查找 node_modules/@babel/core
// 目录作为模块require('./dir'); // 查找 ./dir/index.js 或 ./dir/package.json 的 main 字段require() 缓存机制
// 模块只会被加载一次,之后从缓存返回console.log(require.cache);
// 清除特定模块缓存delete require.cache[require.resolve('./module')];核心模块
Node.js 内置的核心模块,无需额外安装即可使用。
path - 路径操作
const path = require('path');
// 路径拼接path.join('/foo', 'bar', 'baz/asdf');// → '/foo/bar/baz/asdf'
// 解析为绝对路径path.resolve('index.js');// → '/Users/me/project/index.js'
path.resolve('/foo', './bar');// → '/foo/bar'
// 获取路径信息path.basename('/foo/bar/index.js'); // → 'index.js'path.dirname('/foo/bar/index.js'); // → '/foo/bar'path.extname('/foo/bar/index.js'); // → '.js'
// 判断路径类型path.isAbsolute('/foo/bar'); // → truepath.isAbsolute('./foo/bar'); // → false
// 解析路径path.parse('/foo/bar/index.js');// → { root: '/', dir: '/foo/bar', base: 'index.js', ext: '.js', name: 'index' }
// 路径格式化path.format({ dir: '/foo/bar', name: 'index', ext: '.js'});// → '/foo/bar/index.js'
// 跨平台路径分隔符path.sep; // Linux/macOS: '/', Windows: '\\'path.delimiter; // Linux/macOS: ':', Windows: ';'fs - 文件系统
const fs = require('fs');const fsPromises = require('fs').promises; // Promise 风格
// 同步读取const content = fs.readFileSync('./file.txt', 'utf8');
// 异步回调风格fs.readFile('./file.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data);});
// Promise 风格 (Node.js 10+)(async () => { const data = await fsPromises.readFile('./file.txt', 'utf8'); console.log(data);})();
// 同步方法列表fs.readFileSync()fs.writeFileSync()fs.appendFileSync()fs.mkdirSync()fs.rmdirSync()fs.readdirSync()fs.statSync()fs.existsSync()fs.copyFileSync()fs.unlinkSync()fs.renameSync()
// 异步方法列表fs.readFile()fs.writeFile()fs.appendFile()fs.mkdir()fs.rmdir()fs.readdir()fs.stat()fs.access()fs.copyFile()fs.unlink()fs.rename()
// Promise 方法 (fs.promises)fsPromises.readFile()fsPromises.writeFile()fsPromises.mkdir()fsPromises.readdir()fsPromises.stat()fsPromises.access()os - 操作系统信息
const os = require('os');
os.platform(); // 'linux', 'darwin', 'win32'os.arch(); // 'x64', 'arm64'os.release(); // 操作系统版本os.type(); // 'Linux', 'Darwin', 'Windows_NT'os.homedir(); // 用户主目录os.tmpdir(); // 临时文件目录os.hostname(); // 主机名os.EOL; // 换行符 '\n' (Linux/macOS) 或 '\r\n' (Windows)os.cpus(); // CPU 信息os.totalmem(); // 总内存 (bytes)os.freemem(); // 空闲内存 (bytes)os.networkInterfaces(); // 网络接口os.uptime(); // 系统运行时间 (秒)os.loadavg(); // 平均负载 (Linux/macOS)util - 工具函数
const util = require('util');const { promisify } = util;const { callbackify } = util;
// 将回调函数转为 Promiseconst fsReadFile = promisify(fs.readFile);const data = await fsReadFile('./file.txt', 'utf8');
// 将 async 函数转为回调风格const asyncFn = async () => {};const callbackFn = callbackify(asyncFn);
// 格式化字符串util.format('%s:%d', 'hello', 123); // 'hello:123'util.format('%s:%s', 'hello'); // 'hello:%s'
// inspect 对象查看util.inspect({ a: 1, b: { c: 2 } });// → "{ a: 1, b: { c: 2 } }"
// 类型检查util.types.isPromise(p); // 是否为 Promiseutil.types.isArray(arr); // 是否为数组util.types.isDate(date); // 是否为日期util.types.isRegExp(regex); // 是否为正则util.types.isMap(map); // 是否为 Maputil.types.isSet(set); // 是否为 Setutil.types.isAsyncFunction(fn); // 是否为 async 函数util.types.isGeneratorFunction(fn);// 是否为生成器函数events - 事件触发器
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const emitter = new MyEmitter();
// 监听事件emitter.on('event', (arg1, arg2) => { console.log('事件触发', arg1, arg2);});
// 只触发一次的监听器emitter.once('event', () => { console.log('只触发一次');});
// 发送事件emitter.emit('event', '参数1', '参数2');
// 移除监听器emitter.off('event', listenerFn);emitter.removeListener('event', listenerFn);
// 移除所有监听器emitter.removeAllListeners();emitter.removeAllListeners('event');
// 查看监听器数量emitter.listenerCount('event');
// 查看所有监听器emitter.listeners('event');
// 错误事件emitter.on('error', (err) => { console.error('错误:', err);});crypto - 加密模块
const crypto = require('crypto');
// 创建哈希const hash = crypto.createHash('sha256');hash.update('hello');console.log(hash.digest('hex'));
// 创建 HMACconst hmac = crypto.createHmac('sha256', 'secret-key');hmac.update('hello');console.log(hmac.digest('hex'));
// 加密const cipher = crypto.createCipher('aes192', 'password');let encrypted = cipher.update('hello', 'utf8', 'hex');encrypted += cipher.final('hex');
// 解密const decipher = crypto.createDecipher('aes192', 'password');let decrypted = decipher.update(encrypted, 'hex', 'utf8');decrypted += decipher.final('utf8');
// 随机数据crypto.randomBytes(16); // 16 字节随机数据crypto.randomUUID(); // UUID v4
// 生成密钥crypto.generateKey('aes', { length: 256 });
// diffie-hellman 密钥交换const dh = crypto.createDiffieHellman(2048);buffer - 二进制数据
const buffer = Buffer.alloc(10); // 创建 10 字节缓冲区const buffer = Buffer.from('hello'); // 从字符串创建const buffer = Buffer.from([1, 2, 3]); // 从数组创建
// 编码转换buffer.toString('utf8');buffer.toString('hex');buffer.toString('base64');
// 写入buffer.write('hello', 0, 5, 'utf8');
// 拼接Buffer.concat([buf1, buf2, buf3]);
// 复制buf.copy(targetBuf, targetStart, sourceStart, sourceEnd);
// 比较buffer.compare(otherBuffer);
// 切片buffer.slice(0, 5);
// 长度buffer.length;stream - 流
const { Readable, Writable, Transform, Duplex, pipeline } = require('stream');const fs = require('fs');
// 读取流const readStream = fs.createReadStream('./file.txt');readStream.on('data', chunk => { /* 处理数据块 */ });readStream.on('end', () => { /* 读取完成 */ });readStream.on('error', err => { /* 错误处理 */ });
// 写入流const writeStream = fs.createWriteStream('./output.txt');writeStream.write('hello');writeStream.end();writeStream.on('finish', () => { /* 写入完成 */ });
// 管道 (pipe)readStream.pipe(writeStream);
// pipeline (更好的错误处理)pipeline( fs.createReadStream('./file.txt'), gzip(), fs.createWriteStream('./file.txt.gz'), (err) => { if (err) console.error('失败:', err); });
// Transform 流const upperCase = new Transform({ transform(chunk, encoding, callback) { this.push(chunk.toString().toUpperCase()); callback(); }});http / https - HTTP 服务器
const http = require('http');const https = require('https');const fs = require('fs');
// 创建 HTTP 服务器const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World');});
server.listen(3000, '127.0.0.1', () => { console.log('服务器运行在 http://127.0.0.1:3000');});
// HTTP 请求http.get('http://api.example.com/data', (res) => { let data = ''; res.on('data', chunk => { data += chunk; }); res.on('end', () => { console.log(data); });});
// HTTPS 请求const options = { hostname: 'api.example.com', port: 443, path: '/data', method: 'GET'};https.request(options, (res) => { // 处理响应});url - URL 解析
const url = require('url');
// 解析 URLconst myURL = new URL('https://user:pass@host.com:8080/path?query=value#hash');
console.log(myURL.href); // 完整 URLconsole.log(myURL.protocol); // 'https:'console.log(myURL.host); // 'host.com:8080'console.log(myURL.hostname); // 'host.com'console.log(myURL.port); // '8080'console.log(myURL.pathname); // '/path'console.log(myURL.search); // '?query=value'console.log(myURL.searchParams); // URLSearchParamsconsole.log(myURL.hash); // '#hash'console.log(myURL.username); // 'user'console.log(myURL.password); // 'pass'
// URLSearchParamsconst params = new URLSearchParams(myURL.search);params.get('query'); // 'value'params.set('query', 'newvalue');params.append('page', '1');params.has('query'); // trueparams.delete('query');
// 旧式 url.parse (已废弃)url.parse('https://example.com/path?query=value', true);querystring - 查询字符串
const querystring = require('querystring');
// 解析查询字符串querystring.parse('name=test&age=18');// → { name: 'test', age: '18' }
// 构建查询字符串querystring.stringify({ name: 'test', age: 18 });// → 'name=test&age=18'
// 编码querystring.escape('name=test&age=18');// → 'name%3Dtest%26age%3D18'
// 解码querystring.unescape('name%3Dtest');// → 'name=test'zlib - 压缩
const zlib = require('zlib');
// gzip 压缩const gzip = zlib.createGzip();const inp = fs.createReadStream('./file.txt');const out = fs.createWriteStream('./file.txt.gz');inp.pipe(gzip).pipe(out);
// 压缩数据zlib.gzipSync(Buffer.from('hello'));
// 解压数据zlib.unzipSync(Buffer.from(gzipData));
// 其他压缩格式zlib.deflateSync(); // deflatezlib.deflateRawSync(); // raw deflatezlib.brotli*(); // brotli 压缩net - TCP 服务器
const net = require('net');
// 创建 TCP 服务器const server = net.createServer((socket) => { console.log('客户端连接:', socket.remoteAddress);
socket.on('data', (data) => { console.log('收到数据:', data.toString()); socket.write('服务器收到'); });
socket.on('end', () => { console.log('客户端断开'); });
socket.write('欢迎连接');});
server.listen(8080, () => { console.log('TCP 服务器监听 8080 端口');});
// 创建 TCP 客户端const client = net.createConnection(8080, '127.0.0.1', () => { console.log('已连接到服务器'); client.write('Hello Server');});dns - 域名解析
const dns = require('dns');const dnsPromises = require('dns').promises;
// 解析域名dns.resolve4('example.com', (err, addresses) => { if (err) throw err; console.log('IPv4 地址:', addresses);});
dns.resolve6('example.com');dns.resolveMx('example.com');dns.resolveTxt('example.com');dns.resolveNs('example.com');dns.resolveCname('example.com');dns.resolveSoa('example.com');dns.resolveSrv('example.com');dns.reverse('93.184.216.34');
// Promise 风格(async () => { const addresses = await dnsPromises.resolve4('example.com'); console.log(addresses);})();
// 反向解析dns.reverse('93.184.216.34');
// 查找dns.lookup('example.com', (err, address, family) => { console.log('地址:', address, '类型:', family); // family: 4 或 6});process - 进程信息
// 进程信息process.version; // Node.js 版本process.versions; // 依赖库版本process.platform; // 平台 'linux', 'darwin', 'win32'process.arch; // 架构 'x64', 'arm64'process.title; // 进程标题process.pid; // 进程 IDprocess.ppid; // 父进程 ID
// 内存使用process.memoryUsage();// { rss: 23MB, heapTotal: 10MB, heapUsed: 7MB, external: 1MB }
process.memoryUsage().heapUsed; // 堆内存使用量
// CPU 使用process.cpuUsage();// { user: 10000, system: 5000 }
// 运行时间process.uptime(); // 进程运行秒数process.hrtime.bigint(); // 高精度时间 (纳秒)
// 环境变量process.env; // 环境变量对象process.env.NODE_ENV; // 'development', 'production'process.env.PATH;process.env.HOME;
// 命令行参数process.argv; // ['node', 'script.js', 'arg1', 'arg2']process.execArgv; // Node 特殊参数
// 工作目录process.cwd(); // 当前工作目录
// 用户信息process.getuid(); // 用户 IDprocess.getgid(); // 组 IDprocess.groups; // 附加组 ID
// 信号process.on('SIGINT', () => { /* 处理 Ctrl+C */ });process.on('SIGTERM', () => { /* 处理终止信号 */ });
// 退出process.exit(0); // 正常退出process.exit(1); // 异常退出process.kill(pid, 'SIGTERM');
// 下一轮事件循环process.nextTick(() => { /* 异步执行 */ });process.setImmediate(() => { /* 立即执行 */ });
// 错误传播process.on('uncaughtException', (err) => { console.error('未捕获异常:', err);});
process.on('unhandledRejection', (reason, promise) => { console.error('未处理的 Promise 拒绝:', reason);});环境配置
npm 镜像源配置
# 查看当前镜像npm config get registry
# 设置淘宝镜像npm config set registry https://registry.npmmirror.com
# 设置官方镜像npm config set registry https://registry.npmjs.org
# 还原默认镜像npm config set registry https://registry.npmjs.orgnrm - 镜像源管理器
# 安装 nrmnpm install -g nrm
# 查看可用镜像nrm ls
# 切换镜像nrm use taobaonrm use npm
# 添加镜像nrm add <name> <url>
# 删除镜像nrm del <name>
# 测试镜像速度nrm testnrm test taobao
# 查看当前使用的镜像nrm currentcnpm - 淘宝镜像客户端
# 安装 cnpmnpm install -g cnpm --registry=https://registry.npmmirror.com
# 使用 cnpm 代替 npmcnpm install <package>cnpm install
# 或使用 npx 直接运行 cnpmnpx cnpm install <package>.npmrc 配置文件
在用户主目录或项目根目录创建 .npmrc 文件:
# 项目级 .npmrcregistry=https://registry.npmmirror.comprefix=C:\Users\username\.npm-globalcache=C:\Users\username\.npm-cachetmp=C:\Users\username\.npm-tmp# 用户级 .npmrc (~/.npmrc)registry=https://registry.npmmirror.comn 环境管理 (Node 版本切换)
# 全局安装 nnpm install -g n
# 安装稳定版n stable
# 安装最新版n latest
# 安装 LTS 版n lts
# 安装指定版本n 18.17.0
# 切换版本n 16.20.0
# 列出已安装版本n list
# 显示可安装版本n list --all
# 移除版本n rm 14.20.0
# 查看当前版本n
# 使用指定版本执行脚本n use 18.17.0 node script.js常见问题
安装失败
问题:npm 安装报错 EACCES (权限拒绝)
# 解决方案:修改 npm 全局目录权限mkdir ~/.npm-globalnpm config set prefix '~/.npm-global'echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrcsource ~/.bashrc问题:安装卡住不动
# 清理缓存后重试npm cache clean --forcenpm install
# 或使用淘宝镜像npm install --registry=https://registry.npmmirror.com版本问题
Node.js 和 npm 版本不匹配
# 查看版本对应关系# https://nodejs.org/zh-cn/download/releases/# https://nodejs.org/en/download/releases/
# 升级 npmnpm install -g npm
# 升级 Node.js (使用 nvm)nvm install ltsnvm use lts权限问题
问题:全局安装报 EACCES
# 方法 1:使用 nvm 管理 Nodecurl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bashnvm install --ltsnvm use --lts
# 方法 2:修复 npm 目录权限sudo chown -R $(whoami) ~/.npmsudo chown -R $(whoami) /usr/local/lib/node_modules网络问题
问题:下载慢或超时
# 设置国内镜像npm config set registry https://registry.npmmirror.com
# 或使用代理npm config set proxy http://proxy.company.com:8080npm config set https-proxy http://proxy.company.com:8080
# 取消代理npm config delete proxynpm config delete https-proxy其他问题
Windows 下找不到 node_modules/.bin
# 确保在项目根目录执行cd project-dirnpm install
# Windows 下可能需要使用 Git Bash 或 WSL删除 node_modules
# 使用 rimraf (推荐)npm install -g rimrafrimraf node_modules
# 或手动删除rm -rf node_modules # Linux/macOSrd /s /q node_modules # Windows CMDnpm link 使用
# 在开发包目录创建链接cd package-dirnpm link
# 在项目中使用链接cd project-dirnpm link package-name
# 取消链接npm unlink package-namenpm unlink -g package-name相关资源
支持与分享
如果这篇文章对你有帮助,欢迎分享给更多人或打赏支持!

