Files and paths
Read and write files from Node using built-in modules and keep JSON data safe.
- Use node:fs/promises so file work can be awaited.
- Use path.join and fileURLToPath instead of hand-built slashes.
- Parse JSON defensively and handle a missing file with ENOENT.
In plain English
A server often needs to read a file from disk or save data as JSON. Node ships the fs module for reading and writing files, and the promises version of fs lets you use await instead of callbacks. The path module joins folder and file names safely across operating systems. In an ES module, __dirname does not exist, so you build the current folder from import.meta.url with fileURLToPath. When you read a file that may not exist, catch the ENOENT error instead of crashing.
Step by step
- 1Turn import.meta.url into a directory with fileURLToPath and path.dirname.
- 2Read a file with readFile and await the promise.
- 3Parse the text with JSON.parse inside a try/catch.
- 4Catch ENOENT to treat a missing file as empty data, and rethrow anything else.
import { readFile, writeFile, mkdir } from 'node:fs/promises'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const here = path.dirname(fileURLToPath(import.meta.url))
const dataDir = path.join(here, 'data')
const file = path.join(dataDir, 'scores.json')
type Score = {
player: string
score: number
}
async function loadScores(): Promise<Score[]> {
try {
const raw = await readFile(file, 'utf8')
return JSON.parse(raw) as Score[]
} catch (error) {
const code = (error as NodeJS.ErrnoException).code
if (code !== 'ENOENT') throw error
return []
}
}
async function saveScores(scores: Score[]): Promise<void> {
await mkdir(dataDir, { recursive: true })
await writeFile(file, JSON.stringify(scores, null, 2))
}Common mistakes
- Reading a file without a try/catch crashes the whole process the moment the file is missing.
- Using a bare string path like "data/scores.json" breaks when the working directory is different.
- Writing to a folder that does not exist fails, so call mkdir with recursive before writeFile.
- Treating every parse error as a missing file hides real JSON corruption.
Load a JSON file safely
Write loadJson(path) that reads a file, parses it as JSON and returns an empty array when the file is missing. Re-throw other errors.
import { readFile } from 'node:fs/promises'
async function loadJson(filePath) {
const raw = await readFile(filePath, 'utf8')
return JSON.parse(raw)
}Which error code tells you a file you tried to read does not exist?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.