Node.js 知识点整理
Buffer 模块(二进制数据处理)
// 创建 Buffer
const buf = Buffer.from('Hello Node.js', 'utf8');
// 转字符串
console.log(buf.toString()); // Hello Node.js
// 查看二进制
console.log(buf); // <Buffer 48 65 6c 6c 6f 20 4e 6f 64 65 2e 6a 73>fs 模块(文件系统)
const fs = require('fs'); // 引入模块
// 1. 异步读取文件(推荐)
fs.readFile('test.txt', 'utf8', (err, data) => {
if (err) throw err; // 错误处理
console.log('文件内容:', data);
});
// 2. 同步读取文件(阻塞线程,慎用)
const data = fs.readFileSync('test.txt', 'utf8');
// 3. 写入文件(覆盖写入)
fs.writeFile('test.txt', '我是写入的内容', (err) => {
if (!err) console.log('写入成功');
});path 模块(路径处理)
const path = require('path');
// 拼接绝对路径(最常用)
const fullPath = path.join(__dirname, 'test.txt');
console.log('完整路径:', fullPath);
// 获取文件名
console.log(path.basename(fullPath)); // test.txt
// 获取文件扩展名
console.log(path.extname(fullPath)); // .txthttp 模块
const http = require('http');
// 创建服务器
const server = http.createServer((req, res) => {
// 设置响应头
res.writeHead(200, { 'Content-Type': 'text/plain;charset=utf-8' });
// 返回响应内容
res.end('Hello Node.js 原生服务器');
});
// 监听 3000 端口
server.listen(3000, () => {
console.log('服务器运行在 http://localhost:3000');
});基础服务器
const express = require('express');
const app = express();
const PORT = 3000;
// 1. 中间件:解析 JSON 请求体(处理前端 POST 数据)
app.use(express.json());
// 2. 中间件:解决跨域(后面前端结合会详解)
const cors = require('cors');
app.use(cors());
// 3. 路由:处理 GET 请求
app.get('/', (req, res) => {
res.send('Hello Express 服务器');
});
// 4. 动态路由
app.get('/user/:id', (req, res) => {
res.json({ id: req.params.id, name: '前端用户' });
});
// 启动服务
app.listen(PORT, () => {
console.log(`Express 运行在 http://localhost:${PORT}`);
});Node.js 知识点整理
http://localhost:8090/archives/node.js-zhi-shi-dian-zheng-li