How do function(err,data) callbacks work in Node?

; Date: Tue Dec 17 2013

Tags: Node Web Development »»»» Node.JS »»»» Asynchronous Programming

Those new to Node programming might find the callback function pattern a little difficult to understand.  For example how does the data get into the arguments to the function call, and how does the callback function get called?

For example, fs.readFile requires that you pass in a function with this signature:  function(err,data)

Does that mean the function parameters have to be called err and data?  What if the function has more parameters?

The Node.js runtime follows several conventions, one of which is the order of function parameters in callback functions.  The function parameter convention makes it more straight-forward to write callback functions and in other ways inter-operate with the Node runtime.

Convention:  The first parameter, typically called err, is given an error object if there is an error, otherwise it is NULL.

Convention:  The last parameter might be given a callback function, if one is needed for the called function to notify the caller of results or errors.

Because Node.js uses an asynchronous programming model, typical constructs like try/catch, exceptions, and return value conventions, simply do not work in Node.  The asynchronously called function can throw all the exceptions it wants, but they won't be caught by a try/catch located at the site of the function call.

The arguments required for each callback function depends on the needs of the function being called.  You have to consult the documentation for each function.

Callback functions are invoked when a function needs to return data to the caller, send errors to the caller, or to collaborate with code provided by the caller.

About the Author(s)

(davidherron.com) David Herron : David Herron is a writer and software engineer focusing on the wise use of technology. He is especially interested in clean energy technologies like solar power, wind power, and electric cars. David worked for nearly 30 years in Silicon Valley on software ranging from electronic mail systems, to video streaming, to the Java programming language, and has published several books on Node.js programming and electric vehicles.

Books by David Herron

(Sponsored)