1

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

2 Answers2

1

The way writeFile is working is that it is not appending to the file but rather replacing the text in it. This is the reason for the output you get.

You can instead use the function appendFile.

function fileWrite2(savePath) {
    setTimeout(() => {
        for (var i = 0; i < tips.length; i++) {
            fs.appendFile(savePath, tips[i] + "\n", function(err) {
                if (err) throw err;
            });
        }
        console.log('File written sucessfully');
    }, 3000);
}
Sanil Khurana
  • 1,129
  • 9
  • 20
  • It's so strange that I don't have perfect output every time. Sometimes the order of the strings from my array display differently. Should I put the set time function in my for loop – Steven Chen Oct 19 '19 at 06:04
0

fs.writeSync will write the given content into the file, resulting in overwritting the existing content of the file.

If you wish to append to the file you should use fs.appendFileSync for the purpose.

Before that, a quick tip:

You should check if the directory/file is already present or not and then create a new directory if one is not present.

You can do this with fs.ensureDirSync(dir) and fs.mkdirSync(dir)

if (!fs.ensureDirSync(dir)) {
    fs.mkdirSync(dir);
}

Now, you can use fs.appendFileSync to append to your file.

fs.appendFileSync(dir, 'your data!', function(err){
    if(err)
      return err;

    console.log("file saved successfully");
});

The main concept to note here is, any write file operation will replace the file and content whereas, append file operation will append the content at the end of the file.

niranjan_harpale
  • 2,048
  • 1
  • 17
  • 21