最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node.js fs.writeFile: err returns null - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Jun 10, 2017 at 13:31 coras09coras09 3433 silver badges12 bronze badges 2
  • 2 Yes, a null "err" object in async callbacks indicates no errors. – Dennis Commented Jun 10, 2017 at 13:33
  • 1 yep it means no errors – Arpit Solanki Commented Jun 10, 2017 at 13:35
Add a ment  | 

1 Answer 1

Reset to default 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");
    }
});
发布评论

评论列表(0)

  1. 暂无评论