2

i am writing a code in which i have to create files equal to number of elements in a array and write respective array element in files. for example array = [one,two,three], then i want to have file one with content one and so on.

var inputLength = inputs.length;

inputs.forEach(function(elem) {
    i = inputs.indexOf(elem);
    console.log(i);
    fs.writeFile(Execute.path + Execute.folder + "/inputFile" + i, elem, function(err) {
        if (err) {
            console.log(err);
        } else {
            console.log("Input" + i + " file was saved!");
        }

    });


    console.log(i);


});

output of first console.log(i) is fine i.e. 0,1,2,3 so on but output of second console.log(i) is always the index of last element.

whats the problem in my code and how to achieve my goal

Pointy
  • 405,095
  • 59
  • 585
  • 614
Club Flux
  • 31
  • 1
  • 3

1 Answers1

1

It's not about the loops but fs.writeFile() is an asynchronous call, so you need to use IIFE / Closure for this:

var inputLength = inputs.length;

inputs.forEach(function(elem) {
  i = inputs.indexOf(elem);
  (function (i) {
    console.log(i);
    fs.writeFile(Execute.path + Execute.folder + "/inputFile" + i, elem, function(err) {
      if (err) {
        console.log(err);
      } else {
        console.log("Input" + i + " file was saved!");
      }
    });
    console.log(i);
  })(i);
});

The other way of doing the same is to use a synchronous counterpart: fs.writeFileSync().

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
  • after implementing your code i got a error `/home/mritunjay/code-compiler/execute_code.js:77 })(i); ^ TypeError: inputs.forEach(...) is not a function` – Club Flux Jun 19 '18 at 13:42
  • @ClubFlux LoL. No way... That can't happen... Immediately revert back to your original code and check? Even that should throw this error. `:P` – Praveen Kumar Purushothaman Jun 19 '18 at 13:51