W
W
whatThat2019-02-04 00:07:59
JavaScript
whatThat, 2019-02-04 00:07:59

Fs.writeFile in a for loop - write files one by one on each iteration of the loop?

Hello, I'm trying to implement writing files one by one at each iteration of the loop, but the files are written all at once at the first iteration, while the code in the loop continues to be processed correctly. How to solve this problem?

var iterations = n;	
for (var i = 0; i < iterations; i++) {
    jsonData = JSON.stringify(obj[i], null, 2); 
    fs.writeFile("data"+i+".txt", jsonData, function(err) { if (err) { console.log(err);} });
                // More code
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2019-02-04
@whatThat

files are written all at once on the first iteration

Which is not surprising since fs.writeFile is an asynchronous function. Use a synchronous one, or you can write a wrapper that returns a Promise, or you can do it yourself:
const writeFile = (name, data) => new Promise((resolve, reject) => {
  fs.writeFile(name, data, function(err) {
    if (err) {
      reject(err);
    } else {
      resolve();
    }
  });
});

Either using util.promisify :
And use it with await:
for (let i = 0; i < iterations; i++) {
  await writeFile(`data${i}.txt`, JSON.stringify(obj[i], null, 2));
}

A
Andrey, 2019-02-04
@svistiboshka

writeFileSync

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question