Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

223
Views
Using map with NodeJS

I'm running a server with NodeJS and keeping an account. Since the accounts are kept in the map, the map disappears when the server restarts. I prefer to use 'fs' to solve this. When the server starts, take it from a saved folder and set it to map and save the map to a folder every 30 seconds. How can I do this or do you have any other ideas?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If you use JS objects instead of map you can use JSON.stringify method to convert the object to a string and then store it to file system. Imagine something like this:

const database = {"user1": {"some": "data"}, "user2": {"some": "data"}};
const serializedDatabase = JSON.stringify(database);
fs.writeFileSync("./data/database.json", serializedDatabase);

You can run this code inside setInterval loop to make it run every 30 seconds:

setInterval(() => {
    const serializedDatabase = JSON.stringify(database);
    fs.writeFileSync("./data/database.json", serializedDatabase);
}, 30 * 1000);

Then, if you want to read the data once you start you application, just require the file:

const database = require("./data/database.json");

You will get your data in memory. Some points:

  • If you do it this way you can lose data. If your server crashes 20 seconds after last save you are going to lose every data stored to memory in the last 20 seconds.
  • Method writeFile should be probably used instead of writeFileSync to make it non-blocking.
  • In general, storing data to file system by hand is hard and tricky. Using a real database us usually a better call.
  • If you don't have any "big" database such as MySQL or MongoDB, you can use sqlite. It stores all the data to a single file. It's quite easy to use and if you want to migrate it somewhere else you just copy one file.
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!