How can i create global object that i will update with key and value while i use my app?
I need to create global object that i will add more data while the client use the appliaction.
Now i use this :
var json = {}
exports.module = {json}
And this is how i call it :
let json = require("../stroe/store")
But my json value restart to nothing each time that user call the server...
How can i create global object in nodejs?
CodePudding user response:
global.js
const data = {name: "John", surname:"Doe"}
module.export = { data }
The page where you want to use global.js
const usingJSON = require("./global.js")
console.log("result --->", usingJSON)
// It will work when you do the update here
Would you give this a try ?
CodePudding user response:
Your object will not be reset unless the server is restarted.
If you want to store completely permanent data, you need to use a database for this.
In the example below you will see a simple express server example. In every request, I create a new value and add it to the object.
const express = require('express')
const app = express();
const json = {};
app.get("/test", (req, res) => {
json[Math.random()] = Math.random();
console.log(json)
res.status(200).json(json);
});
app.listen(3001);
Result:
{
'0.7194184298804673': 0.8660271960055534,
'0.5781764917107222': 0.7342461283679118,
'0.7488988117603479': 0.8913689704797536
}