Nodejs in-memory storage

2019-04-03 14:50发布

How do I store data to be used for all the clients in my server? (like the messages of a chat)

5条回答
女痞
2楼-- · 2019-04-03 15:01

I wrote Bx for this purpose; it gives you a simple in-memory cache with:

  • Key-value storage
  • Optional expiration on any stored data
  • Support for schemas using JSON-schema

Although I'm plugging my own repository here, I can assure you it works well and it's been used in production at my own company, Onshape for over a year without issues. At the end of the day it's a pretty simple tool; not much to mess up here.

However, if you're storing data that's meant to be permanent you're going to want a database such as MongoDB (w/ Mongoose), MySQL, etc. rather than a cache like Bx or Redis.

查看更多
仙女界的扛把子
3楼-- · 2019-04-03 15:05

If you want more features have a look at redis-node-client

查看更多
干净又极端
4楼-- · 2019-04-03 15:07

The server that node.js allows you to build, is an application server, which means that state is preserved, between request, on the server side. The following snippet demonstrates this:

var sys  = require('sys'),
    http = require('http');

var number = 0;

http.createServer(function (req, res) {
        console.log(req.method, req.url);

        res.writeHead(200, {'Content-Type': 'text/html'});
        res.write('<h1>Number is: ' + number + '</h1>');
        res.end();

        number++;

}).listen(8000);

sys.puts('Server running at http://127.0.0.1:8000/');
查看更多
三岁会撩人
5楼-- · 2019-04-03 15:07

node-cache package is currently the best for key value store and it allows synchronous as well as async storage/retrieval/deletion of keys.

npm link

查看更多
趁早两清
6楼-- · 2019-04-03 15:15

Or use a native node storage mechanism (written in node.js)

http://github.com/felixge/node-dirty

查看更多
登录 后发表回答