Menu
CoddyTech

CommonJS Modules

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

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. Node still runs it in files that end in .cjs, 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
  • Finish countWords(notes) in legacy/stats.cjs: how many words the notes hold together.
  • Import it into notes.js with import stats from './legacy/stats.cjs'.
  • A stats command prints 3 notes, 7 words.

Run node notes.js stats. Then add a note and run stats again: still 3, as nothing is saved yet.

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