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

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

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