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
The "inner block" is a callback to the fs.readFile statement. What happens is
fs.readFile is executed and starts an asynchronous reading of the file.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)));