Answer the question
In order to leave comments, you need to log in
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
files are written all at once on the first iteration
const writeFile = (name, data) => new Promise((resolve, reject) => {
fs.writeFile(name, data, function(err) {
if (err) {
reject(err);
} else {
resolve();
}
});
});
for (let i = 0; i < iterations; i++) {
await writeFile(`data${i}.txt`, JSON.stringify(obj[i], null, 2));
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question