From 67f24d4b0069aa0b542a8865654c54c480c9a874 Mon Sep 17 00:00:00 2001 From: CxJuice <110189934+CxJuice@users.noreply.github.com> Date: Wed, 4 Oct 2023 23:08:15 +0800 Subject: [PATCH] Create server.js --- server.js | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 server.js diff --git a/server.js b/server.js new file mode 100644 index 0000000..e7f1632 --- /dev/null +++ b/server.js @@ -0,0 +1,42 @@ +const express = require('express'); +const fs = require('fs'); +const path = require('path'); + +const app = express(); +const PORT = process.env.PORT || 3000; +const JSON_FOLDER_PATH = path.join(__dirname, 'json'); + +// 获取文件夹内的所有 JSON 文件 +app.get('/json-files', (req, res) => { + fs.readdir(JSON_FOLDER_PATH, (err, files) => { + if (err) { + return res.status(500).send('Server error.'); + } + const jsonFiles = files.filter(file => file.endsWith('.json')); + res.json(jsonFiles); + }); +}); + +// 获取特定的 JSON 文件 +app.get('/json-files/:filename', (req, res) => { + const filePath = path.join(JSON_FOLDER_PATH, req.params.filename); + + fs.readFile(filePath, 'utf8', (err, data) => { + if (err) { + if (err.code === 'ENOENT') { + return res.status(404).send('File not found.'); + } + return res.status(500).send('Server error.'); + } + try { + const jsonData = JSON.parse(data); + res.json(jsonData); + } catch (parseErr) { + res.status(500).send('Error parsing JSON.'); + } + }); +}); + +app.listen(PORT, () => { + console.log(`Server is running on port ${PORT}`); +});