Persistent state in Node.js

This article was originally published at https://gist.github.com/joepie91/bf0813626e6568e8633b.

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);
})

// [...]

Revision #1
Created 11 December 2024 01:56:14 by joepie91
Updated 11 December 2024 18:44:19 by joepie91