4

I'm using 'fs' for writing into a file. The write process is going smoothly, and the file is created as I wanted, but the 'err' variable returns null. I presume this 'null' indicates no errors, but I wanted to be sure.

Is having 'null' from err in fs.writeLine function means there are no errors?

2
  • 2
    Yes, a null "err" object in async callbacks indicates no errors. Commented Jun 10, 2017 at 13:33
  • 1
    yep it means no errors Commented Jun 10, 2017 at 13:35

1 Answer 1

11

Is having 'null' from err in fs.writeFile function means there are no errors?

Yes.

The nodejs asynchronous calling convention that is used for nearly all the asynchronous callbacks in nodejs is to pass two parameters to the callback. The first is the err value and, if it is null (or really any falsey value), then there is no error and the asynchronous result is in the second parameter (if there is a result value).

If err is not falsey, then it represents an error value.

This is often called the nodejs asynchronous calling convention and is used in a ton of nodejs functions.

Here's a reference article that explains/confirms this: What are the error conventions?.

Because fs.writeFile() only has an error/success condition and does not have any other result, the usual way to use fs.writeFile() is like this:

fs.writeFile('someFile', someData, function(err) {
    if (err) {
        // there was an error
        console.log(err);
    } else {
        // data written successfully
        console.log("file written successfully");
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer. I'll handle accordingly then :)
Added reference article.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.