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
Easy- In
format.js, exportformatNote(n, text): it returns1. Buy milkfor1andBuy milk. notes.jsimports it, andaddprintsAdding:followed byformatNote(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'.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Node.js Basics
1Running JavaScript on Node
Hello, NodeCommand-Line ArgumentsCommands