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
Easynotes.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.
- In
format.js, write a functionformatNote(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', andformatNote(3, 'Call Ada')returns'3. Call Ada'. It returns the line; it does not print it. - In
notes.js, importformatNotefrom./format.jsat the top of the file. - In the
addbranch, replace the line that printsAdding: .... It now printsAdding:followed byformatNote(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 milkTry 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'.
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