Menu
CoddyTech

CommonJS Modules

Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 10 of 33.

Much of the Node code you will read, in npm packages and older tutorials, uses another module system.

CommonJS exports with module.exports and imports with require. A file that ends in .cjs is always CommonJS, whatever the rest of the project uses, and an import of such a file gives you its module.exports object as the default:

// greet.cjs
function hello(name) {
    return 'Hello, ' + name;
}
module.exports = { hello };

// app.js
import greet from './greet.cjs';
console.log(greet.hello('Ada'));

exports starts out as the same object as module.exports. exports.hello = hello adds to it; exports = { hello } replaces the variable, and the importer gets an empty object.

challenge icon

Challenge

Easy

An older file, legacy/stats.cjs, is written the CommonJS way, with module.exports. Use it from your notes.js to add a stats command.

  1. In legacy/stats.cjs, finish countWords(notes). It gets the array of notes and returns how many words they hold in total, counted across all the notes. Words are separated by spaces. For the three starting notes, Buy milk, Call Ada and Water the plants, it returns 7. For an empty array it returns 0.
  2. In notes.js, import the file with import stats from './legacy/stats.cjs'. It is a CommonJS file, so stats is its module.exports object, and the function is stats.countWords.
  3. Add a stats command to the chain, before the final else. It prints one line: the number of notes, then the number of words.
    3 notes, 7 words
    where and the other commands keep working.

Try it: type stats in the box after $ node notes.js and press Enter. You see 3 notes, 7 words. Then type add Buy bread, then stats again: you still see 3 notes, 7 words, because the store forgets new notes when the program ends.

Try it yourself

// An older module, written the CommonJS way.
function countWords(notes) {
    // Return how many words all the notes hold together.
    return 0;
}

module.exports = { countWords };

All lessons in Node.js Basics

Practice on your own: Express playground