简体   繁体   中英

How to update in-memory variable in NodeJS?

Let's suppose I have a variable var loli = [ { pop: true}, {pup: false } ] .

Then, I have a route that makes something like this loli.push(req.boy) and another route that responds with the loli array, like this res.json(loli) .

I've searched some questions on Stack, Node Docs and could not figure out why.But my res.json(loli) is only sending the original array, even thought it has changed.

Hou can I watch for changes on this var or tell Node to not cache or do not do whatever it is doing?

It's difficult to say exactly what's wrong without seeing runnable code with the problem, but here's some code that does what you're asking. Fire it up, then go to http://localhost:3000/show to see the initial value of the object, then go to http://localhost:3000/push/foo to push the string value "foo" into the array, and go to http://localhost:3000/show again to see that it's there.

var express = require('express');
var app = express();

var loli = [ { pop: true}, {pup: false } ]

app.get('/push/:boy', function (req, res) {
  loli.push(req.params.boy);
  res.send('Pushed!');
});

app.get('/show', function (req, res) {
  res.json(loli);
});

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM