Menu
CoddyTech

Your First Module

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

notes.js keeps growing, and the code that formats a note will be needed in more than one place.

A module is a file. export in front of a function lets other files use it, and import { name } from './file.js' brings it in:

// math.js
export function add(a, b) {
    return a + b;
}

// app.js
import { add } from './math.js';
console.log(add(2, 3));

Without export the function stays private to math.js, and the import fails. The path starts with ./, meaning the same folder, and it ends with .js: Node does not guess the extension.

challenge icon

Challenge

Easy

notes.js is getting long. Move the code that turns a note into a numbered line into its own file, format.js, so other files can use it too.

  1. In format.js, write a function formatNote(n, text) and export it. It returns the number, a full stop, a space, then the text. formatNote(1, 'Buy milk') returns '1. Buy milk', and formatNote(3, 'Call Ada') returns '3. Call Ada'. It returns the line; it does not print it.
  2. In notes.js, import formatNote from ./format.js at the top of the file.
  3. In the add branch, replace the line that prints Adding: .... It now prints Adding: followed by formatNote(1, text), which is the note numbered 1. Every note is number 1 for now; the real number comes in the next lesson.

node notes.js add Buy milk prints:

Adding: 1. Buy milk

Try it: type add Buy milk in the box after $ node notes.js and press Enter. You see Adding: 1. Buy milk. Then see what Node says about a wrong path: delete .js from the import line in notes.js and run again. The program stops with an error saying it cannot find the module format. Put .js back before you press Check.

Try it yourself

// formatNote(1, 'Buy milk') should return '1. Buy milk'.
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

Practice on your own: Express playground