Amrmsmb
Amrmsmb

Reputation: 1

How to append a line to a file every time I execute it?

I am learning JavaScript and NodeJS. I create a small example as shown in the below posted code. Every time I run the code I expect the file defined in code to accessed and then the same text contained in "data" variable to be appended to it across a new line. But what happens is that, every time I run the code, there is only one line.

How can I fix the code so that every time I run the code a new line is appended.

Code:

var fs = require('fs');
const file = 'c:/testDir/userNodejsTest.txt';
class FileIO {

constructor() {
    if (this.isFileExists()) {
        this.writeToFile();
    }
}

writeToFile() {
    var data = "hey there";
    console.log("[writeToFile]");
    fs.appendFileSync(file, data + "\n", function(err) {
        if(err) {
            console.log(err);
            return false;
        }
        console.log("The file was saved!");
        return true;
    });
}

isFileExists() {
    console.log("[isFileExists]");
    fs.accessSync(file, fs.constants.F_OK, (err) => {
        if (err) {
           console.log("File does not exists");
           return false;
        }
        console.log("File exists");
        return true;
    });
}
}

var fileIO = new FileIO();

module.exports = FileIO;

Upvotes: 0

Views: 66

Answers (1)

Mark
Mark

Reputation: 92440

You are never returning true or false from isFileExists() so writeToFile() is never called. You are passing a callback to fs.accessSync and returning inside that callback, but that not the same. Also, fs.accessSync, is synchronous (hence the name) and doesn't take a callback anyway.

If you are testing for the existence of a file, you probably want fs.existsSync which returns a boolean indicating if the path exists.

With that your function would look more like this:

isFileExists() {
  console.log("[isFileExists]");
  let exists = fs.existsSync(file)
  if (exists) {
    console.log("File exists");
    return true
  }
  console.log("no file")
  return false
}

Of course fs.existsSync() is simple enough you could just use it in the constructor:

constructor() {
    if (fs.existsSync(file)) {
       this.writeToFile();
    }
}

Upvotes: 1

Related Questions