Menu
CoddyTech

Your First Module

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

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
  • In format.js, export formatNote(n, text): it returns 1. Buy milk for 1 and Buy milk.
  • notes.js imports it, and add prints Adding: followed by formatNote(1, text).

Run node notes.js add Buy milk. Then remove .js from the import, run it again to read Node's error, and put it back.

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