Skip to content

File I/O Basics

Understand how programs read and write files, work with file paths, and handle the challenges of file operations.

What you'll learn

  • What file I/O means and why it is different from in-memory operations
  • How programs read file contents into memory
  • How programs write data back to files
  • The importance of file paths and extensions
  • Error handling for missing files and permission issues

Concept

File I/O Basics

File I/O (Input/Output) is how a program interacts with files on disk — reading data from them and writing data to them. Up to now, all your data has lived in memory (variables), which disappears when the program ends. File I/O is how programs achieve persistence: saving data that survives between runs.

Reading Files

Reading a file means loading its contents into memory so your program can work with them. In Node.js, you can read a file synchronously (blocking the program until the file is loaded) or asynchronously (letting the program continue while the file loads in the background):

import { readFileSync } from "fs";

// Synchronous read — simple but blocks the program
const data = readFileSync("config.json", "utf-8");
const config = JSON.parse(data);
console.log(config.setting);

The utf-8 argument tells the system to return the contents as a text string. Without it, you would get raw binary data (a Buffer).

Writing Files

Writing sends data from memory to disk, creating or overwriting a file:

import { writeFileSync } from "fs";

const settings = { theme: "dark", fontSize: 14 };
writeFileSync("config.json", JSON.stringify(settings, null, 2));

JSON.stringify with the null, 2 arguments produces pretty-printed JSON with 2-space indentation — readable by both humans and programs.

File Paths

A file path is the address of a file on the filesystem. Paths can be absolute (starting from the root: /home/user/data.txt on Unix, C:\\Users\\data.txt on Windows) or relative (starting from the current directory: ./data.txt). The file extension (.txt, .json, .csv) hints at the format but does not guarantee it — always validate the content, not just the extension.

Why File I/O Is Different

File operations are fundamentally different from in-memory operations for three reasons:

  1. Speed — disk is thousands of times slower than memory. Reading a large file can take noticeable time.
  2. Failure — files might not exist, might be locked by another process, or the program might lack permission. You must handle these errors.
  3. Concurrency — other programs can modify or delete a file while you are reading it. File I/O requires defensive coding.

Error Handling

Always wrap file operations in error handling. A missing file is not a bug in your logic — it is a normal runtime condition that your program should handle gracefully:

try {
  const data = readFileSync("maybe-missing.json", "utf-8");
} catch (error) {
  console.log("File not found, using defaults");
  // fall back to default configuration
}

This pattern — try to read, catch and fall back — is the standard approach for optional configuration files.

Example

              import { readFileSync, writeFileSync, existsSync } from "fs";

// --- Read a JSON config file with error handling ---
function loadConfig(path) {
  if (!existsSync(path)) {
    console.log("Config not found, creating default");
    return { theme: "light", language: "en" };
  }
  try {
    const raw = readFileSync(path, "utf-8");
    return JSON.parse(raw);
  } catch (error) {
    console.log("Config is corrupt, using default:", error.message);
    return { theme: "light", language: "en" };
  }
}

// --- Save config back to disk ---
function saveConfig(path, config) {
  const json = JSON.stringify(config, null, 2);
  writeFileSync(path, json, "utf-8");
  console.log("Config saved to", path);
}

// Usage:
const config = loadConfig("app-config.json");
config.theme = "dark";
config.lastOpened = new Date().toISOString();
saveConfig("app-config.json", config);
            

loadConfig checks if the file exists, tries to read and parse it, and falls back to defaults on any error. saveConfig serializes the config to pretty JSON and writes it. This is a real pattern used in desktop and server applications.

Try it

  • JSON Formatter

    Formatting JSON is the first step after reading a file. Paste file contents and format them for inspection.

  • JSON Validator

    Before parsing a file's contents, validate the JSON. This tool catches syntax errors that would crash JSON.parse.

Common mistakes

The mistake

Not handling the case where a file does not exist or is unreadable.

The fix

Always use try/catch around file reads, or check with existsSync first. A missing file is a normal condition, not a crash-worthy error. Fall back to defaults gracefully.

The mistake

Assuming a file's extension guarantees its content format.

The fix

A .json file might contain invalid JSON. Always parse inside try/catch and validate the structure after parsing. Never trust the extension alone.

The mistake

Reading an entire large file into memory at once.

The fix

For large files, use streaming APIs that process data in chunks instead of loading it all at once. This prevents memory exhaustion on multi-gigabyte files.

Related Cheatsheets

  • Bash Cheatsheet

    Command-line file operations — ls, cat, mv, cp — the shell side of file I/O.

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors