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

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

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 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