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

237
Visualizações
NodeJS FileSystem Json Read and Write only one works

for a school project I have to rewrite a Json Object using node fs. I wrote a module and if I use deleteCity or addCity on their own, they work perfectly fine. But when I call both after another only one works. In my JSON File there is one array with 10 objects. In my main javascript file I require my module and call upon addCity and deleteCity functions.

//Modules
const fs = require("fs");

//Variablen
const citiesPath = "./cities.json";

//Funktionen
const deleteCity = (name) => {
    fs.readFile(citiesPath, "utf-8", (err, jstring) => {
        if (err) {
            console.log(err);
        }
            try {
                let data = JSON.parse(jstring);
                for (let i = 0; i < data.length; i++) {
                    if (data[i].Name == name) {
                        data.splice(i, 1);
                    }
                }
                fs.writeFile(citiesPath, JSON.stringify(data, null, 2), (err) => {
                    if (err) {
                        console.log(err);
                    }
                });
            } catch (error) {
                console.log(error);
        }
    });
};

const addCity = (obj) => {
    fs.readFile(citiesPath, "utf-8", (err, jstring) => {
        if (err) {
            console.log(err);
        } 
            try {
                let data = JSON.parse(jstring);
                data.push(obj);
                fs.writeFile(citiesPath, JSON.stringify(data, null, 2), (err) => {
                    if (err) {
                        console.log(err);
                    }
                });
            } catch (error) {
                console.log(error);
        }
    });
};

const showCity = () => {
    fs.readFile(citiesPath, "utf-8", (err, jstring) => {
        if (err) {
            console.log(err);
        } 
            try {
                let data = JSON.parse(jstring);
                console.log(data);
            } catch (error) {
                    console.log(error);
        }
    });
};


//Exporte
module.exports = {
    deleteCity,
    addCity,
    showCity
};

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I suppose you are calling both function synchronously, i.e.

deleteCity("London");
addCity({ "Name": "Paris" });

The problem here is that the calls are both asynchronous and the second one will start before the first call terminates, so basically before a city has been deleted.

If this is a school project the simplest solution to fix your code is using the synchronous version of the fs calls fs.readFileSync and fs.writeFileSync:

//Modules
const fs = require("fs");

//Variablen
const citiesPath = "./cities.json";

//Funktionen
const deleteCity = (name) => {
    const jstring = fs.readFileSync(citiesPath, "utf-8");
    let data = JSON.parse(jstring);
    for (let i = 0; i < data.length; i++) {
        if (data[i].Name == name) {
            data.splice(i, 1);
        }
    }
    fs.writeFileSync(citiesPath, JSON.stringify(data, null, 2));
};

const addCity = (obj) => {
    const jstring = fs.readFileSync(citiesPath, "utf-8");
    let data = JSON.parse(jstring);
    data.push(obj);
    fs.writeFileSync(citiesPath, JSON.stringify(data, null, 2));
};

const showCity = () => {
    const jstring = fs.readFileSync(citiesPath, "utf-8");
    let data = JSON.parse(jstring);
    console.log(data);
};


//Exporte
module.exports = {
    deleteCity,
    addCity,
    showCity
};

Note that you don't need to catch the errors only to log them inside your synchronous functions. If an error is thrown and not caught, Node.js will log it for your.

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