gpt4 book ai didi

javascript - Node js中读取动态json数据

转载 作者:太空宇宙 更新时间:2023-11-04 00:09:03 25 4
gpt4 key购买 nike

我有一个 express 服务器。

服务器.js

const express = require('express');
const app = express();
var json = require("./sample.js")
app.use("/", (req, res)=>{
console.log("----------->", JSON.stringify(json));
res.status(200).send(JSON.stringify(json));
});

app.listen(2222,()=>{
console.log(`Listening on port localhost:2222/ !`);
});

示例.js

var offer = {
"sample" : "Text",
"ting" : "Toing"
}

module.exports = offer ;

一旦我执行server.js文件,它就会从sample.js文件中获取json数据。如果我在 server.js 仍在执行时更新 example.js 的数据,我不会获得更新的数据。有什么办法吗 执行相同的操作,而不停止 server.js 的执行。

最佳答案

是的,有一种方法,您必须在每次请求发生时读取该文件(或者将其缓存一段时间,以获得更好的性能)。

require 不起作用的原因是 NodeJS 会自动为您缓存模块。因此,即使您在请求处理程序中需要它(在 use 中),它也不会工作。

因为您无法使用 require,所以使用模块并不方便(或性能不佳)。因此您的文件应该采用 JSON 格式:

{
"sample" : "Text",
"ting" : "Toing"
}

要读取它,您必须使用fs(文件系统)模块。这允许您每次都从磁盘读取文件:

const fs = require('fs');
app.get("/", (req, res) => {
// To read as a text file, you have to specify the correct
// encoding.
fs.readFile('./sample.json', 'utf8', (err, data) => {
// You should always specify the content type header,
// when you don't use 'res.json' for sending JSON.
res.set('Content-Type', 'application/json');
res.send(data)
})
});

重要的是要知道,现在 data 是一个字符串,而不是一个对象。您需要 JSON.parse() 来获取对象。

在这种情况下也不建议使用使用。对于中间件,您应该考虑使用 get (如我的示例),或者如果您想处理任何动词,则应考虑使用 all

关于javascript - Node js中读取动态json数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50822768/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com