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

495
Visualizações
How to return empty array if file doesn't exists in NodeJS

I would like to console.log a message and return an empty array if I try to read a file that doesn't exist. The getAllNotes function fires effective and the error is definitely thrown no such file or directory, open 'notes.json'.

However, why is the error thrown if I didn't specify throw err in my if statement? Secondly why doesn't my console.log message get outputted and the empty array not returned?

var getAllNotes = () => {
  console.log("MADE IT TO GET ALL NOTES")
  var notesArray = fs.readFileSync('notes.json', (err, data) => {
    if (err) {
      console.log("There are no notes to display");
      return [];
    } else {
      console.log("DATA",data)
      console.log("MADE IT TO PARSE")
      return JSON.parse(data);
    }
  });
  console.log("INSIDE GET ALL NOTES", notesArray)
};
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

fs.readFileSync is a blocking call and doesn't take a callback in the same way that fs.readFile does. It simply returns the contents of the file, see the below example:

var fs = require('fs');
var date = fs.readFileSync('myfile', 'utf8');
console.log(data);

When I ran your example an exception is thrown because you are providing a callback function where it is expecting a string or object for the options parameter.

You can do a blocking call with fs.existsSync(path) to check if the file exists before trying to read it.

Alternatively you can use the non-blocking version of the readFile and provide the callback as you were trying to do.

over 4 years ago · Santiago Trujillo 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