Menu
CoddyTech

Built-in Modules

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

Your notes will soon live in a file, and file paths differ from one computer to the next.

Node ships its own modules for this. You import them like your files, with a node: prefix and nothing to install. path.join glues parts of a path with the right separator, path.basename gives the last part, os.homedir() is your home folder, and process.cwd() is the folder the program runs in.

import os from 'node:os';
import path from 'node:path';

const file = path.join(os.homedir(), 'photos', 'cat.png');
console.log(file); // /home/ada/photos/cat.png
console.log(path.basename(file)); // cat.png

path.join puts one slash between the parts, so you never get photoscat.png.

challenge icon

Challenge

Easy
  • A new where command prints the full path of notes.json in the current folder: path.join(process.cwd(), 'notes.json').
  • A second line prints that path's base name.

Run node notes.js where. The file does not exist yet: chapter 3 creates it.

Try it yourself

// Your notes tool starts here.
import { formatNote } from './format.js';
import store from './store.js';

const [command, ...words] = process.argv.slice(2);
const text = words.join(' ');

if (command === 'add') {
    const n = store.add(text);
    console.log(`Adding: ${formatNote(n, text)}`);
} else if (command === 'list') {
    const owner = process.env.NOTES_OWNER ?? 'you';
    console.log(`Notes for ${owner}`);
    if (store.notes.length === 0) {
        console.log('No notes yet');
    }
    store.notes.forEach((note, i) => console.log(formatNote(i + 1, note)));
} else {
    if (command) {
        console.error(`Unknown command: ${command}`);
    }
    console.error('Usage: node notes.js <command> [words]');
    process.exit(1);
}
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