Menu
CoddyTech

Event Emitters

Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 20 of 24.

The store should announce that a note was added without knowing who wants to hear it.

An EventEmitter from node:events keeps a list of listeners for each event name. on(name, fn) adds a listener; emit(name, ...args) calls every listener for that name, straight away, with those arguments. A listener added after the emit hears nothing.

import { EventEmitter } from 'node:events';

const door = new EventEmitter();
door.on('open', (who) => console.log(`${who} came in`));
door.on('open', () => console.log('Ding!'));
door.emit('open', 'Ada');
// Ada came in, then Ding!

To turn an existing object into an emitter, copy its methods onto one: Object.assign(new EventEmitter(), { ... }).

challenge icon

Challenge

Easy
  • Make store an emitter that emits added with the note's text and number after saving.
  • notes.js listens for added and prints Saved note 4. from the listener.

Run node notes.js add Buy bread. Then clear and add two notes to watch the numbers start again.

Try it yourself

import { existsSync } from 'node:fs';
import { readFile, writeFile } from 'node:fs/promises';

const file = 'notes.json';

const readJson = async (name, fallback) => {
    if (!existsSync(name)) {
        return fallback;
    }
    try {
        return JSON.parse(await readFile(name, 'utf8'));
    } catch (err) {
        console.error(`${name} is damaged: ${err.message}`);
        process.exit(1);
    }
};

const [notes, settings] = await Promise.all([readJson(file, []), readJson('settings.json', {})]);

const store = {
    notes,
    settings,
    async save() {
        await writeFile(file, JSON.stringify(this.notes, null, 2));
    },
    async add(text) {
        this.notes.push(text);
        await this.save();
        return this.notes.length;
    },
    async remove(n) {
        const [text] = this.notes.splice(n - 1, 1);
        await this.save();
        return text;
    },
};

export default store;
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Node.js Basics