Node.js基础用法
一、基础用法与核心模块
1. 运行 Node.js 脚本
bash
# 运行 JS 文件
node script.js# 进入交互式环境(REPL)
node
2. 核心模块示例
文件系统(fs
模块)
javascript
const fs = require('fs').promises; // 异步 Promise 版本
const path = require('path');// 读取文件
async function readFile() {try {const content = await fs.readFile(path.join(__dirname, 'test.txt'), 'utf8');console.log(content);} catch (err) {console.error('读取失败:', err);}
}// 写入文件
async function writeFile() {try {await fs.writeFile('output.txt', 'Hello Node.js', 'utf8');console.log('写入成功');} catch (err) {console.error('写入失败:', err);}
}
HTTP 服务器(http
模块)
javascript
const http = require('http');const server = http.createServer((req, res) => {res.writeHead(200, { 'Content-Type': 'text/plain' });res.end('Hello World\n');
});server.listen(3000, () => {console.log('服务器运行在 http://localhost:3000');
});
路径处理(path
模块)
javascript
const path = require('path');// 拼接路径
const fullPath = path.join(__dirname, 'src', 'app.js');
console.log(fullPath); // 输出绝对路径// 解析路径
console.log(path.parse(fullPath)); // 输出路径详情(root、dir、base等)
二、包管理(npm/yarn/pnpm)
1. 初始化项目
bash
# 创建 package.json
npm init -y # 快速生成默认配置
yarn init -y
2. 安装依赖
bash
# 生产依赖(会写入 dependencies)
npm install lodash
yarn add lodash# 开发依赖(会写入 devDependencies)
npm install --save-dev eslint
yarn add --dev eslint# 全局安装
npm install -g nodemon
yarn global add nodemon
3. 运行脚本(package.json)
在 package.json
中定义脚本:
json
{"scripts": {"start": "node server.js","dev": "nodemon server.js", // 热重载开发"test": "jest"}
}
运行脚本:
bash
npm run start # 或 npm start(简写)
yarn dev
三、模块化系统(CommonJS 与 ES Modules)
1. CommonJS 模块(默认)
javascript
// 导出(module.exports)
// math.js
function add(a, b) { return a + b; }
module.exports = { add };// 导入(require)
// app.js
const { add } = require('./math');
console.log(add(1, 2)); // 3
2. ES Modules(需配置)
在 package.json
中添加:
json
{ "type": "module" }
使用 ES 模块语法:
javascript
// 导出(export)
// math.js
export function add(a, b) { return a + b; }// 导入(import)
// app.js
import { add } from './math.js'; // 必须带 .js 后缀
console.log(add(1, 2)); // 3
四、常用开发工具与配置
1. 热重载(nodemon)
监控文件变化并自动重启服务:
bash
# 安装
npm install -g nodemon# 运行
nodemon server.js # 替代 node server.js
2. 环境变量(dotenv)
管理环境变量(如数据库密码):
bash
npm install dotenv
创建 .env
文件:
env
DB_HOST=localhost
DB_PORT=3306
在代码中使用:
javascript
require('dotenv').config();
console.log(process.env.DB_HOST); // localhost
3. 调试配置(VS Code)
创建 .vscode/launch.json
:
json
{"version": "0.2.0","configurations": [{"type": "node","request": "launch","name": "启动程序","program": "${workspaceFolder}/server.js"}]
}
按 F5 启动调试。
五、常用框架与库
1. Web 框架
Express(轻量):
javascript
const express = require('express'); const app = express();app.get('/', (req, res) => {res.send('Hello Express'); });app.listen(3000, () => console.log('服务启动在 3000 端口'));
Koa(Express 团队开发,更现代):
javascript
const Koa = require('koa'); const app = new Koa();app.use(ctx => {ctx.body = 'Hello Koa'; });app.listen(3000);
2. 数据库操作
MySQL(使用
mysql2
):javascript
const mysql = require('mysql2/promise');async function query() {const connection = await mysql.createConnection({host: 'localhost',user: 'root',database: 'test'});const [rows] = await connection.execute('SELECT * FROM users');console.log(rows); }
MongoDB(使用
mongoose
):javascript
const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/test');const User = mongoose.model('User', { name: String }); const user = new User({ name: 'Node.js' }); await user.save();
六、命令行工具开发
使用 commander
库快速开发 CLI:
bash
npm install commander
示例(cli.js
):
javascript
const { program } = require('commander');program.version('1.0.0').command('greet <name>').description('问候用户').action((name) => {console.log(`Hello, ${name}!`);});program.parse(process.argv);
运行:
bash
node cli.js greet World # 输出 "Hello, World!"
七、常用配置文件
.npmrc
(npm 配置):ini
registry=https://registry.npmmirror.com # 切换为淘宝镜像
eslintrc.js
(代码规范):javascript
module.exports = {env: { node: true, es2021: true },extends: 'eslint:recommended',parserOptions: { ecmaVersion: 'latest' }, };
jest.config.js
(测试配置):javascript
module.exports = {testEnvironment: 'node', };