0
0
Node.jsframework~5 mins

Error-first callback convention in Node.js

Choose your learning style9 modes available
Introduction
The error-first callback convention helps handle errors and results clearly in asynchronous code. It keeps your code organized and easy to understand.
When reading a file and you want to know if it failed or succeeded.
When making a network request and you need to handle errors or data.
When querying a database and want to process results or errors.
When performing any asynchronous task that might fail or succeed.
Syntax
Node.js
function callback(err, result) {
  if (err) {
    // handle error
  } else {
    // use result
  }
}
The first argument is always the error (or null if no error).
The second argument is the successful result data.
Examples
Reads a file and logs error or file content.
Node.js
import fs from 'fs';

fs.readFile('file.txt', (err, data) => {
  if (err) {
    console.error('Error:', err);
  } else {
    console.log('File data:', data.toString());
  }
});
Queries a database and handles error or results.
Node.js
db.query('SELECT * FROM users', (err, rows) => {
  if (err) {
    console.error('DB error:', err);
  } else {
    console.log('Users:', rows);
  }
});
Sample Program
This program tries to read 'example.txt'. If the file does not exist or another error happens, it prints the error message. Otherwise, it prints the file content.
Node.js
import fs from 'fs';

function readFileCallback(err, data) {
  if (err) {
    console.log('Failed to read file:', err.message);
  } else {
    console.log('File content:', data.toString());
  }
}

fs.readFile('example.txt', readFileCallback);
OutputSuccess
Important Notes
Always check for errors first before using the result.
If you forget to handle errors, your program might crash or behave unexpectedly.
This pattern is common in Node.js core modules and many libraries.
Summary
Error-first callbacks always pass error as the first argument.
Check if error exists before using the result.
This keeps asynchronous code clear and safe.