I am trying to use fs.writeFile to loop from an array of strings to create a new text file. I use fs.writeSync and it worked. However, when I use fs.writeFile, the content in the text file that I created does not show every item in my array. Instead, the result is more like some incomplete strings of my array. I use the setTime() function to set it for 3 seconds and still does not show complete results in my text file.
The fs.writeSync one works perfectly
function fileWriteSync(filePath) {
const fd = fs.openSync(filePath, 'w');
for (var i = 0; i < tips.length; i++) {
fs.writeSync(fd, tips[i] + '\n');
console.log(tips[i]);
}
fs.closeSync(fd);
}
tips = [
"Work in teams",
"get enough sleep",
"be on time",
"Rely on systems",
"Create a rough weekly schedule",
"Get rid of distractions before they become distractions",
"Develop good posture",
"Don’t multitask",
"Cultivate the belief that intelligence isn’t a fixed trait",
"Work in short blocks of time", "Exercise regularly",
"Be organized", "Break big tasks into smaller ones",
"Take notes during class", "Ask lots of questions",
"Eat healthily",
"Do consistent work",
"Manage your thoughts and emotions",
"Give yourself rewards",
"Manage your stress"
]
function fileWrite2(savePath) {
setTimeout(() => {
for (var i = 0; i < tips.length; i++) {
fs.writeFile(savePath, tips[i] + "\n", function(err) {
if (err) throw err;
});
}
console.log('File written sucessfully');
}, 3000);
}
fileWrite2('tips3.txt')
My current output:
Manage your stress s and emotions ence isn’t a fixed trait