Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

221
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda