Built-in Modules: fs, path, os — Node.js

Node's built-in modules work with no install: require("node:fs/promises") for files, require("node:path") for file addresses, require("node:os") for computer…

In the previous lesson, the notes were written straight into notes.js. To add a single note, you had to edit the code. It's easier when the data is kept in its own file, and the program reads that file. JavaScript in the browser isn't allowed to read files from the disk.

In Node it is, and the tools are already there with no npm install: Node's built-in modules. This lesson uses three:

Built-in modules: just require them

Take all three with require, as in the previous lesson:

const fs = require("node:fs/promises");
const path = require("node:path");
const os = require("node:os");

The node: prefix marks a module built into Node. Without the prefix, require("fs") works too. With it, a reader sees right away that this isn't a package from npm. node:fs/promises is the version of fs whose functions return Promises, so you can use them with await.

fs: reading a file

The notes-api project now keeps its data in the file data/notes.json. It holds an array of the same two notes as in the previous lesson. Here is the app.js that reads it:

async function main() {
  const filePath = path.join(__dirname, "data", "notes.json");
  console.log(filePath);
  try {
    const content = await fs.readFile(filePath, "utf8");
    const notes = JSON.parse(content);
    console.log(notes.length + " notes read");
  } catch (err) {
    console.log(err.message);
  }
}

main();
$ node app.js
/home/budi/notes-api/data/notes.json
2 notes read

Almost every fs function has three styles:

The callback and Sync styles are in require("node:fs"), without /promises. The Sync version blocks the event loop. The event loop is the part of Node that does all its tasks in turn. While a file is read with Sync, Node can't do anything else, including answering other requests. That's fine in a script you run once, or while a server starts. But don't use it in a request handler, the function that answers each request on a server.

path: building file addresses

__dirname holds the folder of the file that is running. path.join joins the parts of an address with the right separator (the sign between folder names) for the computer's OS (operating system). Compare three ways to build the same address:

Code Linux and macOS Windows
path.join(__dirname, "data", "notes.json") /home/budi/notes-api/data/notes.json C:\Users\budi\notes-api\data\notes.json
__dirname + "/data/notes.json" /home/budi/notes-api/data/notes.json C:\Users\budi\notes-api/data/notes.json
__dirname + "data/notes.json" /home/budi/notes-apidata/notes.json C:\Users\budi\notes-apidata/notes.json

Look at the last row. __dirname doesn't end with a slash, so notes-api and data stick together into notes-apidata. That address doesn't exist, so the result is ENOENT. The middle row works on Linux. On Windows, the separators are mixed: \ and then /. Node on Windows can still open it. But a path like that isn't cross-platform (not the same on every OS), and it breaks easily when compared with another path or handed to another program. So use path.join. It picks the right separator and tidies doubled slashes.

Other path functions you'll use often, with the filePath from the code above:

os: info about the machine

Some of the info os gives:

console.log(os.platform()); // "linux", "darwin" (macOS), or "win32" (Windows)
console.log(os.cpus().length); // number of CPU cores, for example 8
console.log(os.homedir()); // "/home/budi"

os helps a program adapt to its machine, for example to use every CPU core (later, in the clustering lesson).

In ES Modules, there is no __dirname

An ES Modules file that writes __dirname fails with ReferenceError: __dirname is not defined in ES module scope. The replacement is import.meta.dirname, available since Node 20.11. For the address of the file itself, use import.meta.filename.

In the exercise: a pretend fs

The exercise simulator has no real disk. So its "file system" (where files are kept) is a files object, which maps file names to their content. In the exercise, you write two functions. readFile(filepath) returns a file's content, or throws an error with throw new Error("File not found") when that name isn't there. transform(filepath) reads the file inside a try. Then it uppercases the text with toUpperCase(), takes its extension with path.extname, and prints:

notes.txt -> ext: .txt, content: HELLO WORLD
data.json -> ext: .json, content: {"X":1}
missing.txt -> Error: File not found

⚠️ A slow server, odd file contents, or ENOENT

TL;DR: Node's built-in modules work with no install: require("node:fs/promises") for files, require("node:path") for file addresses, require("node:os") for computer info. Read a file with await fs.readFile(filePath, "utf8") inside try/catch. A missing file gives err.code "ENOENT". readFileSync blocks the event loop (the part of Node that does its tasks in turn): while the file is read, Node answers no other request. So don't use it in a request handler (the function that answers a request). Build addresses with path.join(__dirname, "data", "notes.json"), where __dirname holds the folder of the running file. The separator between folder names is / on Linux and macOS and \ on Windows, so joining with + isn't cross-platform (not the same on every operating system). path.extname takes the extension, os.platform() gives the operating system's name. In ES Modules, import.meta.dirname replaces __dirname.

⚡ Built-in modules, no install

Write:

const fs = require("node:fs/promises");
const path = require("node:path");

Meaning: Node has built-in modules, with no npm install: for files (fs), file addresses (path) and machine info (os). The node: prefix marks a built-in module, not a package from npm. node:fs/promises is the version of fs that works with await.

⚡ Read a file without blocking

Write:

const content = await fs.readFile(filePath, "utf8");
const notes = JSON.parse(content);

Meaning: filePath holds the file's address. readFile returns the file's content as text ("utf8"), and await waits for it without stopping Node's other work. Write this code inside an async function, and wrap it in try/catch: a missing file gives err.code "ENOENT". Don't use readFileSync in a request handler (the function that answers a request). readFileSync blocks the event loop (the part of Node that does its tasks in turn): Node answers no other request until the file has been read.

⚡ Build addresses with path.join

Write:

const filePath = path.join(__dirname, "data", "notes.json");
Guess first: Windows uses \ between folder names. "uploads" + "/" + name (name holds a file name) works on your laptop. Why is it still a problem on Windows?

The separators get mixed: \ from a Windows folder address and the / you wrote. A path like that isn't cross-platform (not the same on every operating system), and it breaks easily.

Meaning: __dirname holds the folder of the running file. path.join picks the right separator for the operating system: / on Linux and macOS, \ on Windows.

What you will learn