0
0
Node.jsframework~5 mins

Events vs callbacks decision in Node.js

Choose your learning style9 modes available
Introduction

Events and callbacks help your program respond to actions or changes. Choosing between them makes your code easier to understand and work with.

When you want to run code after something finishes, like reading a file.
When multiple parts of your program need to react to the same action.
When you want to keep your code simple and easy to follow.
When you want to handle things happening at different times in your app.
When you want to avoid deeply nested code that is hard to read.
Syntax
Node.js
/* Callback example */
function doTask(callback) {
  // do something
  callback(null, 'done');
}

doTask((err, result) => {
  if (err) {
    console.error(err);
  } else {
    console.log(result);
  }
});

/* Event example */
const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.on('done', (result) => {
  console.log(result);
});

emitter.emit('done', 'done');

Callbacks are functions passed to run after a task finishes.

Events let many listeners react to named signals from an object.

Examples
Callback example: run code after reading a file.
Node.js
const fs = require('fs');
fs.readFile('file.txt', (err, data) => {
  if (err) throw err;
  console.log(data.toString());
});
Event example: multiple parts can listen for 'message' events.
Node.js
const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.on('message', (msg) => {
  console.log('Received:', msg);
});

emitter.emit('message', 'Hello!');
Sample Program

This program shows both ways: an event emitter and a callback. Both wait 1 second and then print a message.

Node.js
const EventEmitter = require('events');

class Task extends EventEmitter {
  run() {
    setTimeout(() => {
      this.emit('done', 'Task completed');
    }, 1000);
  }
}

// Using events
const task = new Task();
task.on('done', (msg) => {
  console.log('Event says:', msg);
});
task.run();

// Using callback
function runTask(callback) {
  setTimeout(() => {
    callback('Callback says: Task completed');
  }, 1000);
}

runTask((message) => {
  console.log(message);
});
OutputSuccess
Important Notes

Use callbacks for simple, single responses.

Use events when many parts need to react or for more flexible design.

Events can help avoid deeply nested callbacks, making code cleaner.

Summary

Callbacks run one function after a task finishes.

Events let many listeners respond to named signals.

Choose callbacks for simple tasks, events for complex or multiple reactions.