Idiomatic successful callback in Node.js

By convention in Node, an asynchronous callback accepts an error as its first argument. If successful, the first argument should not be present. I personally wrote

callback(undefined, result); 

in this case. However, I see other people in the code

 callback(null, result); 

prevailing. Is it "officially" documented anywhere? Which of the two options is the idiomatic Node? Are there any good reasons to prefer each other?

+7
javascript idioms asynchronous
source share
3 answers

If we interpret the "idiomatic Node" as "what Node himself does," then null will be what is idiomatic. If you type this at the Node prompt (on * nix machine), you will get true :

 require("fs").readFile("/dev/null", function (err) { console.log(err === null) }) 

I tried with other callbacks from the fs module and got the same behavior. I have not tested all the places in the Node API where callbacks are used.

I did not find a link that says Node should set err to null in such cases.

+9
source share

If you are worried about using null vs undefined, go to a null value. Strictly speaking, in JavaScript, undefined is considered abnormal.

You can learn more about this. What is the difference between zero and undefined in JavaScript? .

There is also a good publication on Node.js callback conventions - http://blog.gvm-it.eu/post/22040726249/callback-conventions-in-node-js-how-and-why .

+3
source share

In case of errors, undefined and null always considered the same.

You can use both of them. People use null just because they are shorter.

If you check for errors, you can check both null and undefined in a single expression using the if (err == null) { ... } approach.

0
source share

All Articles