在小型网站或者个人项目的开发中,我们往往不需要复杂的企业级后台架构,使用Node.js搭建轻量级后台就能满足文本内容与图片资源的管理需求,既降低了部署成本,也提升了开发效率。

环境准备与基础框架搭建
首先确保本地已经安装Node.js环境,然后初始化项目并安装必要的依赖包。我们需要Express作为Web框架,multer用于处理文件上传,body-parser解析请求体,fs和path模块处理文件操作。
# 初始化项目 npm init -y # 安装依赖 npm install express multer body-parser
接下来创建基础的服务入口文件,搭建基础的服务框架:
const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const app = express();
// 解析application/json类型的请求体
app.use(bodyParser.json());
// 解析application/x-www-form-urlencoded类型的请求体
app.use(bodyParser.urlencoded({ extended: true }));
// 静态资源目录,用于访问上传的图片
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
// 确保上传目录存在
const uploadDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
}
const PORT = 3000;
app.listen(PORT, () => {
console.log(`服务运行在 http://127.0.0.1:${PORT}`);
});文本管理功能实现
文本管理主要实现文本的添加、查询、修改和删除功能,我们可以先用一个本地数组作为临时存储,实际项目中可以替换为数据库。首先定义文本数据的基础接口:
// 临时文本存储数组
let textList = [];
let textId = 1;
// 添加文本接口
app.post('/api/text', (req, res) => {
const { content } = req.body;
if (!content) {
return res.status(400).json({ code: 400, message: '文本内容不能为空' });
}
const newText = {
id: textId++,
content,
createTime: new Date().toISOString()
};
textList.push(newText);
res.json({ code: 200, message: '添加成功', data: newText });
});
// 查询所有文本接口
app.get('/api/text', (req, res) => {
res.json({ code: 200, data: textList });
});
// 修改文本接口
app.put('/api/text/:id', (req, res) => {
const id = parseInt(req.params.id);
const { content } = req.body;
const textItem = textList.find(item => item.id === id);
if (!textItem) {
return res.status(404).json({ code: 404, message: '文本不存在' });
}
if (content) {
textItem.content = content;
}
res.json({ code: 200, message: '修改成功', data: textItem });
});
// 删除文本接口
app.delete('/api/text/:id', (req, res) => {
const id = parseInt(req.params.id);
const index = textList.findIndex(item => item.id === id);
if (index === -1) {
return res.status(404).json({ code: 404, message: '文本不存在' });
}
textList.splice(index, 1);
res.json({ code: 200, message: '删除成功' });
});图片上传管理功能实现
图片上传我们使用multer中间件来处理,首先配置multer的存储规则,指定上传文件的存储目录和文件名格式:
// 配置multer存储
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, uploadDir);
},
filename: function (req, file, cb) {
// 生成唯一文件名,避免重名
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
const ext = path.extname(file.originalname);
cb(null, file.fieldname + '-' + uniqueSuffix + ext);
}
});
// 过滤上传的文件类型,只允许图片
const fileFilter = (req, file, cb) => {
const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
if (allowedTypes.includes(file.mimetype)) {
cb(null, true);
} else {
cb(new Error('只允许上传图片类型文件'), false);
}
};
const upload = multer({ storage: storage, fileFilter: fileFilter });接下来实现图片上传的接口,同时可以添加获取已上传图片列表的接口:
// 图片上传接口,单个文件上传,字段名photo
app.post('/api/upload', upload.single('photo'), (req, res) => {
if (!req.file) {
return res.status(400).json({ code: 400, message: '未上传文件或文件类型不符合要求' });
}
// 返回图片的访问地址
const fileUrl = `http://127.0.0.1:${PORT}/uploads/${req.file.filename}`;
res.json({ code: 200, message: '上传成功', data: { url: fileUrl, filename: req.file.filename } });
});
// 获取已上传图片列表接口
app.get('/api/images', (req, res) => {
fs.readdir(uploadDir, (err, files) => {
if (err) {
return res.status(500).json({ code: 500, message: '读取文件列表失败' });
}
const imageList = files.map(file => {
return {
filename: file,
url: `http://127.0.0.1:${PORT}/uploads/${file}`
};
});
res.json({ code: 200, data: imageList });
});
});接口测试与异常处理
完成接口开发后,我们可以使用Postman或者curl命令测试接口是否正常。测试文本添加接口:
curl -X POST http://127.0.0.1:3000/api/text \
-H "Content-Type: application/json" \
-d '{"content": "这是一段测试文本内容"}'测试图片上传接口:
curl -X POST http://127.0.0.1:3000/api/upload \ -F "photo=@/path/to/your/test.jpg"
为了提升后台的健壮性,我们可以添加全局的异常处理中间件,捕获multer上传文件时的错误:
// 全局错误处理中间件
app.use((err, req, res, next) => {
if (err instanceof multer.MulterError) {
// multer相关错误
return res.status(400).json({ code: 400, message: `文件上传错误: ${err.message}` });
} else if (err) {
// 其他错误
return res.status(400).json({ code: 400, message: err.message });
}
next();
});总结
到这里我们就完成了一个轻量级Node.js网站后台的文本与图片管理功能,整个方案没有依赖复杂的框架,代码量较少,适合小型项目快速落地。如果需要更复杂的功能,可以在此基础上扩展数据库存储、权限验证、图片压缩等能力,满足更多场景的需求。