0

I am facing some issue in the function that I am using to handle errors while writing something into a file. In this function I would like to show the file name that has just been written, however, I my error function only shows the last file name and not the rest. Why is this? Is a scope issue?

My code

var myArray = ["A","B","C"]
// File variable
const fileHandler = require('fs');

for (let currentArrayElement in myArray ){

    hexFile = myArray[currentArrayElement];
        hexFile += ".hex"

        console.log("hexFile---->"+hexFile);
        // Writting serilaNumberInHex into a .hex file called hexFile
        fileHandler.writeFile(hexFile,"blabla" , function(err) {
            if(err) {
                return console.log(err);
            }
            console.log("[Info] File " + hexFile + " was succesfully created");
        }); 
}

Output

hexFile---->A.hex
hexFile---->B.hex
hexFile---->C.hex
[Info] File C.hex was succesfully created
[Info] File C.hex was succesfully created
[Info] File C.hex was succesfully created
[Finished in 0.2s]

Expected output

hexFile---->A.hex
hexFile---->B.hex
hexFile---->C.hex
[Info] File A.hex was succesfully created
[Info] File B.hex was succesfully created
[Info] File C.hex was succesfully created
[Finished in 0.2s]

[Solution] Thanks to Durga

My code

var myArray = ["A","B","C"]
// File variable
const fileHandler = require('fs');

for (let currentArrayElement in myArray ){

    let hexFile = myArray[currentArrayElement];
        hexFile += ".hex"

        console.log("hexFile---->"+hexFile);
        // Writting serilaNumberInHex into a .hex file called hexFile
        fileHandler.writeFile(hexFile,"blabla" , function(err) {
            if(err) {
                return console.log(err);
            }
            console.log("[Info] File " + hexFile + " was succesfully created");
        }); 
}
ndarkness
  • 1,011
  • 2
  • 16
  • 36

0 Answers0