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
how can i throw an error if exist and stop writing with node fs?

I have found an error writing a wrong variable, when writing the file, due to that error, the file has been written wrong, deleting everything that was in it, leaving it blank.

fs.writeFile(
  path.join(__dirname,"../example/path/file.json") , 
  JSON.stringify(var)
);

How can i make: "If error exist, dont try to write the file and throw an error via console"

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You read the documentation and open/write to the file with the correct flags:

const fs = require('fs/promises');

async function writeFile(fn, content) {
    const opts  = {

        // assuming that content is a string
        encoding: 'utf8',

        // 'wx' opens a file for writing.
        // The file is created if it does not exist,
        // and rejects if the file does exist.
        flag: 'wx', 

    };

    // returns undefined on success, or an error
    return await fs
                 .writeFile(fn, content, opts)
                 .catch( err => err )
                 ;
}
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