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

214
Visualizações
Why is the data not written to the file?

I have this code which is supposed to write data in text file:

const test = [
  'test1',
  'test2'
]
fs.writeFile('file.txt', test, {flag: "a"}, err => {
  if (err) throw err
})

The problem is that code works without errors, but there is no data in file. If I just put and execute this piece of code in some test file, it works correctly, but not in function, where this code is supposed to be. What's wrong? Why there is no data in file if I execute code in function, but everything works correctly, when I execute it in test file?

Here is the code of function:

const fs = require("fs");

(async () => {
    const test = [
      'test1',
      'test2'
    ]
    fs.writeFile('file.txt', test, {flag: "a"}, err => {
      if (err) throw err
    })

    process.exit(1);
  } catch (e) {
    console.log('error: ', e)
    process.exit(1)
  }
})()
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You're missing the "try" part of your try/catch.

You're also exiting the script before the file is written.

try writeFileSync instead.

const fs = require("fs");

(async() => {
  const test = [
    'test1',
    'test2'
  ]
  try {
    fs.writeFileSync('file.txt', test, {
      flag: "a"
    });
    process.exit(1);
  } catch (e) {
    console.log('error: ', e)
    process.exit(1)
  }
})()
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