Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Node Stateful? Can Node maintain variables in memory

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.

like image 776
William Falcon Avatar asked Jul 21 '26 03:07

William Falcon


1 Answers

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

like image 60
hairyhenderson Avatar answered Jul 23 '26 18:07

hairyhenderson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!