Reputation: 29
I have an express server.
server.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/ !`);
});
sample.js
var offer = {
"sample" : "Text",
"ting" : "Toing"
}
module.exports = offer ;
Once i execute the server.js file, it fetches the json data from sample.js file. If I update the data of the sample.js while the server.js is still executing I dont get updated data. Is there any way to do the same, without stopping the execution of server.js.
Upvotes: 2
Views: 7288
Reputation: 111
Yes, there is a way, you have to read the file every time a request occurs (or cache it for a time, for a bit better performance).
The reason why require
does not work is that NodeJS automatically caches modules for you. So even if you would require it inside the request handler (in the use
), it won't work.
Because you cannot use require
, it won't be convenient (or performant) to use a module. So your file should be in JSON format instead:
{
"sample" : "Text",
"ting" : "Toing"
}
To read it, you have to use the fs
(file system) module. This allows you to read the file from disk every time:
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)
})
});
It is important to know, that now data
is a string, not an object. You would need JSON.parse()
to get an object.
Also use
is not recommended in this case. It is for middlewares, you should consider using get
(as in my example), or all
if you want to handle any verb.
Upvotes: 2
Reputation: 2929
You need to read the file at runtime:
fs = require('fs');
function getJson() {
fs.readFile('sample.json', (err, jsonData) => {
if (err) {
console.log('error reading sample.js ', err)
}
return(jsonData)
}
}
}
make sure your sample.js is instead just a json object.
Upvotes: 1