Reputation: 351
I built a small app with NodeJS and Hapi. There is some data that should be held in memory for as long as the app is running. For instance, our company keeps a list of "blocked words" in the database.
What I want:
When the app starts, we fetch this data from the database, and then store the data in a global variable. We never hit the database again for this data. We assume this app will be restarted every week or two.
My fear:
If this was a PHP app, it would make this database query every time the page loaded. I would have to use something like Memcache to hold the data. Otherwise I'd be abusing the database with hundreds of extra calls each minute.
My ideal:
If I could use Java or Clojure it would be trivially easy to load the data at launch and then hold it in memory for as long as the app was running.
So which model does NodeJS follow? PHP or Clojure?
Upvotes: 0
Views: 72
Reputation: 39456
Your node application has persistent data in memory from when it boots through to when it's killed. You can store data in a global variable and it will persist between connections.
You can easily confirm this by declaring a variable, incrementing it each time a request comes into your application, and logging the result:
let counter = 0;
const server = require('http').createServer((req, res) => {
counter++;
res.statusCode = 200;
res.end(counter.toString());
console.log(counter);
});
server.listen(3000);
Note: This example will increment twice on each request when using a browser that request a
favicon
.
Upvotes: 1