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

83
Vistas
readFile reads my file after the rest of the code executes

Im hoping I colould get some insite. The readFile reads my file after the rest of the code executes. I need the information from the file in order to use it within the rest of the code. I have been doing research on synchronous and asynchronous but I cant figure out how it applies.

This is my readfile code and below it other code begins that is dependent on the data within this file.

const carPartlist = () => {
  const fs = require('fs');
  fs.readFile("doc.csv", "utf8", (error, textContent) => {
    if (error) {
      throw error;
    }

    for (let row of textContent.split("\n")) {
      const rowItems = [row.split(",")];
      console.log(rowItems);
    }
  })
}
carPartlist();
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

It's a good idea to read async (to not block your app on a synchronous read). Do it like this...

const carPartlist = async () => {
  const fs = require('fs').promises; // node >= 10
  const textContent = await fs.readFile("doc.csv", "utf8");

  for (let row of textContent.split("\n")) {
    const rowItems = [row.split(",")];
    console.log(rowItems);
  }
}

carPartlist();

EDIT maybe I'm being misunderstood because I ended the snippet where the OP's ended. The complete OP code probably executes code before and/or after carPartList. Work that must be done after can be coded one of two ways:

// at the top level
carPartlist().then(() => {
  // code here that depends on carPartList being run
  // presumably, the more complete OP code does something with the data it reads
})

// or, in a function
async functionThatRunsEarly() {
  await carPartlist();
  // code here that depends on carPartList being run
}

Per the OP's question (and contrary to some of the comments), this is the right way to do file i/o, this does not block the app's thread, this and does cause the "code here that depends on carPartList" (and the post-reading code in that function) to execute after the read.

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