Skip to content

Instantly share code, notes, and snippets.

@joepie91
Last active April 2, 2022 12:49
Show Gist options
  • Save joepie91/bf0813626e6568e8633b to your computer and use it in GitHub Desktop.
Save joepie91/bf0813626e6568e8633b to your computer and use it in GitHub Desktop.
Persistent state in Node.js

This is an extremely simple example of how you have 'persistent state' when writing an application in Node.js. The i variable is shared across all requests, so every time the /increment route is accessed, the number is incremented and returned.

This may seem obvious, but it works quite differently from eg. PHP, where each HTTP request is effectively a 'clean slate', and you don't have persistent state. Were this written in PHP, then every request would have returned 1, rather than an incrementing number.

var i = 0;
// [...]
app.get("/increment", function(req, res) {
i += 1;
res.send("Current number: " + i);
})
// [...]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment