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

198
Vistas
Inner block of a code is getting executed after the first block in node js

According to this "1" was to be printed first and then "2". BUt it is giving a wrong output.

fs.readdir("./my_stocks", (err, files) => {
    for(each in files){
        var file=files[each];
        if(file!='portfolio.js'){
            var fn="./my_stocks/"+file;
            fs.readFile(fn,(err,data)=>{
                var arr=data.toString().split('\n');
                console.log(1);
                fs.appendFile("./my_stocks/portfolio.js",JSON.stringify(stock_detail),(err)=>{
                    if(err) throw err;
                });
            });
            console.log(2)
        }
    }
});

output:

2 2 1 1

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

0

The "inner block" is a callback to the fs.readFile statement. What happens is

  1. fs.readFile is executed and starts an asynchronous reading of the file.
  2. The next statement is executed, outputting a "2".
  3. Steps 1 and 2 are repeated for each file in the directory, so that two "2"'s are outputted altogether.
  4. Later, when the reading of a file is completed, the "inner block" is executed, outputting a "1".
  5. Since two files are being read altogether, step 4 is executed twice and two "1"'s are output. But the first "1" being output does not necessarily belong to the first file being read, because a shorter file may have finished reading before a longer one, even if it started later.

If you want to avoid such asynchronousness, you can use fs.readFileSync (and also fs.readdirSync). But this will slow down the overall execution, because files are then read one after the other, not in parallel. If the order of the entries in your portfolio.js does not matter, asynchronousness is therefore preferable.

Note, however, that appending several stock_details to one portfolio.js does not make valid Javascript overall:

{"Stock 1":100}{"Stock 2":200}

Assuming that every file contains lines such as

A: 1
B: 2

(without a final newline), you can read and process them asynchronously with the "promises flavor" of the fs package:

const fs = require("fs/promises");
fs.readdir("./my_stocks")
.then(function(files) {
  var promises = [];
  for(each in files){
    var file=files[each];
    if(file!='portfolio.js'){
      var fn="./my_stocks/"+file;
      promises.push(fs.readFile(fn)
        .then(data => data.toString().split('\n')));
    }
  }
  return Promise.all(promises);
})
.then(portfolio => fs.writeFile("./my_stocks/portfolio.js", JSON.stringify(portfolio)));
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