0Pricing
Node.js Backend Development Bootcamp · 课时

使用文件系统与流

学习如何在 Node.js 中使用 fs 模块同步或异步读写文件,并了解流如何帮助您高效处理大量数据。

使用文件系统与流 是 CoddyKit 上的免费 Node.js Backend Development Bootcamp 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Node.js Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Node.js Backend Development Bootcamp 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why the File System Matters

Most backends eventually read or write files on disk — logs, config, uploads, reports. Node's built-in fs module handles it all; just require it.

const fs = require('fs');
console.log(typeof fs.readFile);

Synchronous vs Asynchronous

Most fs methods come in two flavors: sync (like readFileSync) blocks the event loop, async doesn't. On servers, always prefer async.

const fs = require('fs');
const data = fs.readFileSync('config.txt', 'utf8');
console.log(data);

Reading a File Asynchronously

The classic callback form gives you error first, then data. Always check err before touching the data — a missing file or bad permission lands there.

const fs = require('fs');
fs.readFile('notes.txt', 'utf8', (err, data) => {
  if (err) { console.error('Failed:', err.message); return; }
  console.log('File says:', data);
});

The Promise-Based API

Modern Node exposes a promise-based API under fs/promises — pairs perfectly with async/await and skips callback nesting entirely.

const fs = require('fs/promises');
async function load() {
  const data = await fs.readFile('notes.txt', 'utf8');
  console.log(data);
}
load();

Writing Files

Use writeFile to create or overwrite a file. No file? It's created. File exists? Its contents are replaced wholesale.

const fs = require('fs/promises');
async function save() {
  await fs.writeFile('output.txt', 'Hello from Node!');
  console.log('Saved.');
}
save();

Appending Instead of Overwriting

To add to a file without wiping it, use appendFile — exactly what you want for log files that grow line by line.

const fs = require('fs/promises');
async function log(line) {
  await fs.appendFile('app.log', line + '\n');
}
log('Server started');

Working with Paths

Hard-coded paths break across operating systems. The path module fixes that: path.join uses the right separator, and __dirname is the current file's folder.

const path = require('path');
const full = path.join(__dirname, 'data', 'users.json');
console.log(full);

Checking If a File Exists

Don't check existence first — that risks race conditions. Just try the operation and catch the error; a missing file throws with code ENOENT.

const fs = require('fs/promises');
async function read() {
  try {
    return await fs.readFile('maybe.txt', 'utf8');
  } catch (err) {
    if (err.code === 'ENOENT') return 'default content';
    throw err;
  }
}

Why Streams Exist

Reading a 2 GB file with readFile loads it all into memory — a crash waiting to happen. Streams process data in small chunks, keeping memory low.

const fs = require('fs');
const stream = fs.createReadStream('huge.log', 'utf8');
stream.on('data', chunk => console.log('Got', chunk.length, 'bytes'));

Piping Streams Together

The power move with streams is pipe: connect a readable straight to a writable. Node handles backpressure so a fast reader won't flood a slow writer.

const fs = require('fs');
const read = fs.createReadStream('input.txt');
const write = fs.createWriteStream('copy.txt');
read.pipe(write);

Listing and Creating Directories

The fs module manages folders too: mkdir creates directories (add { recursive: true } for nested paths), and readdir lists contents.

const fs = require('fs/promises');
async function setup() {
  await fs.mkdir('uploads', { recursive: true });
  const files = await fs.readdir('.');
  console.log(files);
}
setup();

Quick Check

Test your understanding of file operations.

Recap

You can now work the file system: fs's sync/callback/promise APIs, async on servers, basic I/O, cross-platform path, and streams for big files.

常见问题解答

「使用文件系统与流」课时是免费的吗?

是的 — 「使用文件系统与流」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Node.js Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 Node.js Backend Development Bootcamp 课程共包含 4 节课。

「使用文件系统与流」这节课中我会学到什么?

学习如何在 Node.js 中使用 fs 模块同步或异步读写文件,并了解流如何帮助您高效处理大量数据。 你通过在浏览器中直接运行的动手代码来练习 Node.js Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Node.js Backend Development Bootcamp 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Node.js Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「使用文件系统与流」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Node.js Backend Development Bootcamp 课中编写并运行代码吗?

能。每节 Node.js Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Node.js 与 NPM 入门
  2. 详解 Node.js 模块系统
  3. 异步 JavaScript 与事件循环
  4. 使用文件系统与流
← 返回 Node.js Backend Development Bootcamp