appendFile() runs before readFile() even though appendFile() is chronologically after the readFile()

172 Views Asked by At

I am trying to write code that reads a file, counts the lines in it, and then adds another line with the line's number in the beginning. Like an index, basically. The problem is that the fs.appendFile() starts running before fs.readFile() is finished, but I am not sure as to why. Is there something I am doing wrong?

My code:

fs.readFile('list.txt', 'utf-8', (err, data) => {
    if (err) throw err;

    lines = data.split(/\r\n|\r|\n/).length - 1;

    console.log("Im supposed to run first");

});
console.log("Im supposed to run second");


fs.appendFile('list.txt', '[' + lines + ']' + item + '\n', function(err) {
    if (err) throw err;
    console.log('List updated!');

    fs.readFile('list.txt', 'utf-8', (err, data) => {
        if (err) throw err;

        // Converting Raw Buffer dto text 
        // data using tostring function. 
        message.channel.send('List was updated successfully! New list: \n' + data.toString());
        console.log(data);
    });

});

My output:

Im supposed to run second
List updated!
Im supposed to run first
[0]first item

enter image description here

2

There are 2 best solutions below

0
Tristan On

Currently, you are using readFile and appendFile. Both of these functions are asynchronous and will run at the same time, returning whenever they complete.

If you'd like to run these synchronously, you can use the fs.readFileSync and fs.appendFileSync methods to synchronously read and append to the files.

Therefore, with something like the following:

const readFileData = fs.readFileSync("list.txt");

fs.appendFileSync('list.txt', '[' + lines + ']' + item + '\n');

The first line of code will run, then the second line of code.

0
Raphael Deiana On

The functions you are using are asynchronous, so the response of the second function can be received before the response of the first one.

fs.readFile('list.txt', 'utf-8', (err, data) => {
    if (err) throw err;

    lines = data.split(/\r\n|\r|\n/).length - 1;

    console.log("Im supposed to run first");
    appendFile(lines);

});


let appendFile = (lines)=> {
    fs.appendFile('list.txt', '[' + lines + ']' + item + '\n', function(err) {
        console.log("Im supposed to run second");
        if (err) throw err;
        console.log('List updated!');

        fs.readFile('list.txt', 'utf-8', (err, data) => {
            if (err) throw err;

            // Converting Raw Buffer dto text 
            // data using tostring function. 
            message.channel.send('List was updated successfully! New list: \n' + data.toString());
            console.log(data);
        });

    });
}