Node.js Foundations·From script to service

Files and paths

Read and write files from Node using built-in modules and keep JSON data safe.

Intermediate 12 min read Lesson 1 of 300 Challenge included
What you will be able to do
  • 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

  1. 1Turn import.meta.url into a directory with fileURLToPath and path.dirname.
  2. 2Read a file with readFile and await the promise.
  3. 3Parse the text with JSON.parse inside a try/catch.
  4. 4Catch ENOENT to treat a missing file as empty data, and rethrow anything else.
store.tsTypeScript
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.
Your turn

Load a JSON file safely

Easy

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.

JAVASCRIPT · starter
import { readFile } from 'node:fs/promises'

async function loadJson(filePath) {
  const raw = await readFile(filePath, 'utf8')
  return JSON.parse(raw)
}
Check your understanding before moving on.
Knowledge checkQuestion 1

Which error code tells you a file you tried to read does not exist?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Environment and config
Lesson 1 of 300 · 0% of course