简体   繁体   中英

How to declare a static array in Node.js?

I am trying to create a static array named "categories" whom I wish it will be initialized ONCE in my Node.js application. I mean, when I close the app and run it again - I want it to KEEP the state of the "categories" array. What happens is that the array is initialized for each time I run this app. Though I want it to be declared only once in this app's lifetime.

router.post("/add_category", (req, res, next) => {
   var category = req.body.category;
   categories.push(category);
   res.render("index", { categories });
});

You should need a database for that kind of data persistence. But at times, a full-blown database (MongoDB, SQL) could be considered overkill since you only need to save a simple array. So, consider using the "node-persist" package, here's a possible solution:

const storage = require('node-persist');
storage.initSync();
storage.setItem('categories', [ . . . ] );
console.log(storage.getItem('categories'));

The simplest solution is to just write the array to a file as JSON and then load that back in when your server starts.

let categories = require('./categories.json');

router.post("/add_category", (req, res, next) => {
   var category = req.body.category;
   categories.push(category);
   fs.writeFile(`./categories.json`, JSON.stringify(categories), () => {
       res.render("index", { categories });
   });
});

Node.js, by itself, does not have any automatically persisted variables that get saved to disk by themselves and are automatically available the next time you run the program. You have to code that yourself.

That is was databases are for. Consider Using some SQL or noSQL database that will store values even if server is reseted.

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