Skip to content

File I/O 基础

理解如何 programs 读取 and 编写 files, 工作使用 file paths, and handle challenges 的 file 操作.

你将学到

  • 什么 file I/O 平均值 and 为什么它 是不同从 in-memory 操作
  • 如何 programs 读取 file 内容到 memory
  • 如何 programs 编写数据后面到 files
  • importance 的 file paths and extensions
  • 错误 handling for missing files and permission issues

概念讲解

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("配置.JSON", JSON.stringify(settings, null, 2));

JSON.stringify with the 空, 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:\\用户\\数据.txt on Windows) or relative (starting from the current directory: ./数据.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 不找到, using defaults");
  // fall back to default configuration
}

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

示例代码

              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 检查如果 file exists, tries 到读取 and parse 它, and falls 后面到 defaults on 任何错误. saveConfig serializes 配置到 pretty JSON and 编写它. 这个是 真实模式 used in desktop and 服务器 applications.

动手试一试

  • JSON Formatter

    格式化 JSON 是首先步骤之后读取 file. 粘贴 file 内容 and 格式它们 for inspection.

  • JSON Validator

    之前 parsing file's 内容, 验证 JSON. 这个 tool catches 语法错误那个会 crash JSON.parse.

常见错误

错误写法

不 handling 情况哪里 file 做不 exist or 是 unreadable.

正确做法

总是 use try/catch 围绕 file 读取, or 检查使用 existsSync 首先. missing file 是 normal 条件, 不 crash-worthy 错误. Fall 后面到 defaults gracefully.

错误写法

Assuming file's extension guarantees 它的内容格式.

正确做法

.JSON file 可能包含无效 JSON. 总是 parse 内部 try/catch and 验证结构之后 parsing. 从不 trust extension alone.

错误写法

读取整个大 file 到 memory at 一次.

正确做法

For 大 files, use streaming APIs 那个处理数据 in 块相反的 加载它 所有 at 一次. 这个 prevents memory exhaustion on multi-gigabyte files.

相关速查表

  • Bash Cheatsheet

    Command-行 file 操作 — ls, cat, mv, cp — shell 边的 file I/O.

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误