Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

225
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda