0

Here is the sourcecode:

console.log('Starting app.');

const fs = require('fs');

fs.appendFile('greetings.txt', 'Hello world!');

fs.appendFileSync('greetings.txt', 'Hello world!');

when i load the app in the terminal, it keeps giving me this error message.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
Vally
  • 1

1 Answers1

0

fs.appendFile() is the asynchronous version of that interface and it requires that the last argument be a callback that gives you both completion and/or error conditions.

See the doc.

fs.appendFile(path, data[, options], callback)

The callback is NOT optional.

The proper usage of that function would be this:

fs.appendFile('greetings.txt', 'Hello world!', err => {
    if (err) {
         console.log(err);
    } else {
         console.log("data appended successfully");
    }
});

Also, please note that this is asynchronous and non-blocking so the callback will get called some indeterminate time later (when the append finishes), but the next lines of code after this will execute immediately (before the callback is called).


Other relevant interfaces are the promise version of the asynchronous interface:

fs.promises.appendFile(path, data[, options])

You do not pass a callback to this version. Instead, it returns a promise which you use to get notified of completion/error.

fs.promises.appendFile('greetings.txt', 'Hello world!').then(() => {
    console.log("data appended successfully");
}).catch(err => {
    console.log(err);
});

For asynchronous interfaces, the promise-version is newer and considered more modern.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • @Vally - Since it looks like you may be new here, if this worked, then you can indicate that to the community by clicking the checkmark to the left of the answer. That will also earn you some reputation points here on stackoverflow for following the proper procedure with your question. – jfriend00 Apr 16 '22 at 04:45