7

By convention in Node, an asynchronous callback accepts an error as its first argument. In case of success, the first argument must not be present. I personally used to write

callback(undefined, result);

in that case. However, I see in other people's code

callback(null, result);

prevailing. Is it "officially" documented anywhere? Which of the two options is idiomatic Node? Are there any significant reasons to prefer one over another?

Ivan Krechetov
  • 18,802
  • 8
  • 49
  • 60
  • If the callback follows the idiomatic way of checking that argument (i.e. `if (error)` or `if (!error)`), then it does not make any difference. If the callback insists on strict checking (e.g. `error === null` or `error !== undefined`), then you will have to pass the value it expects in the first place. – Frédéric Hamidi Mar 26 '14 at 10:27
  • Yeah this more like how you define the meaning of undefined and null. – Risto Novik Mar 26 '14 at 11:31

3 Answers3

9

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

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

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

I've not found a reference that states that Node must set err to null in such cases.

Louis
  • 146,715
  • 28
  • 274
  • 320
  • I see no reason for testing it when you can just take a look at the source code of any these modules in the `lib/` folder of the Node.js source package (or on GitHub). – Ilya I Mar 26 '14 at 14:40
3

If you are concerned whether to use null vs undefined, then go with null. Strictly speaking in JavaScript undefined is considered to be abnormal.

You can read more on this at What is the difference between null and undefined in JavaScript?.

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

Community
  • 1
  • 1
Ilya I
  • 1,282
  • 1
  • 12
  • 19
0

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

You can use both of them. People use null only because it's shorter.

If you're checking for errors, you can check for both null and undefined in one statement using if (err == null) { ... } approach.

alex
  • 11,935
  • 3
  • 30
  • 42