7

Is Node stateful?

If I want to build an index to keep in memory, will it persist throughout different connections? I'm just wondering if this is possible. For example we have a server in java that maintains a hashmap in memory to speed up certain search queries. It modifies it as things come in. Would this be possible in Node?

Thanks.

William Falcon
  • 9,813
  • 14
  • 67
  • 110

3 Answers3

8

Absolutely. Here's a dead-simple example of what I think you're looking for (modified sample code from http://nodejs.org):

var http = require('http');
var foo = 0;
http.createServer(function (req, res) {
  foo += 1;
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('You are foo number ' + foo + '\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

Note that this sort of thing often isn't done except for the most transient sort of data. If you something a little more persistent, look at using something like redis

hairyhenderson
  • 577
  • 1
  • 7
  • 20
3

Yes, you can keep state in your process that persists in memory for the lifetime of the process. There are libraries available for hashmaps, LRU caches, and other commonly-used data structures.

Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
2

You can have the equivalent to static variables in node. The first time a file is required node will run the code in that file. Which means that if you define variables on a scope level equal or higher than the module.exports, you will always have access to those variables from inner closures.

(function(){
  var aStaticVariable = 123;

  module.exports = function() {
    // an instantiable object

  }
})();

You also have global variables:

global.aGlobalVar = "foo";
fmsf
  • 36,317
  • 49
  • 147
  • 195