Skip to content

Instantly share code, notes, and snippets.

@joepie91

joepie91/_note.md

Last active Nov 9, 2015
Embed
What would you like to do?
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
You can’t perform that action at this time.