//index.js
const express = require("express")
const querystring = require("querystring");
const fs = require('fs');
const path = require('path');
const filePath = path.join(__dirname, 'data.json'); // 文件路径
const app = express()
const bodyParser = require("body-parser");//body参数解析
app.use(bodyParser.urlencoded({ extended: false })); //parse application/x-www-form-urlencoded
app.use(bodyParser.json()); //parse application/json
app.get('/', (req, res) => {
res.send("添加文字转视频服务。")
})
app.get('/getVideoList', (req, res) => {
fs.readFile(filePath, 'utf-8', function (err, data) {
if (err) throw err;
res.send(data)
});
})
//删除
app.get('/delVideo', (req, res) => {
let id = req.query.video_id;
// 读取 JSON 文件
fs.readFile(filePath, 'utf-8', function (err, data) {
if (err) throw err;
const jsonData = JSON.parse(data);
// 删除数据
for(let i = 0; i < jsonData.length; i++){
if(id == jsonData[i]['video_id']){
jsonData.splice(i, 1);
}
}
// 将修改后的 JavaScript 对象重新写回到 JSON 文件中
fs.writeFile(filePath, JSON.stringify(jsonData), function (err) {
if (err) throw err;
res.send({
code: 200,
msg: '删除成功',
data: null
})
});
});
})
// 新增
app.post('/addVideo', (req, res) => {
let addData = req.body;
// 读取 JSON 文件
fs.readFile(filePath, 'utf-8', function (err, data) {
if (err) throw err;
const jsonData = JSON.parse(data);
// // 添加数据
jsonData.push(addData);
// 将修改后的 JavaScript 对象重新写回到 JSON 文件中
fs.writeFile(filePath, JSON.stringify(jsonData), function (err) {
if (err) throw err;
res.send({
code: 200,
msg: '添加成功',
data: jsonData
})
});
});
})
app.listen(8888, () => {
console.log("服务器启动成功! 端口8888")
})