0Pricing
Node.js Backend Development Bootcamp · レッスン

ファイルシステムとストリームの操作

Node.jsのfsモジュールを使って、同期・非同期の両方でファイルを読み書きする方法を学びます。さらに、ストリームで大量のデータを効率的に処理する方法も身につけます。

「ファイルシステムとストリームの操作」はCoddyKit上の無料Node.js Backend Development Bootcampレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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.

よくある質問

「ファイルシステムとストリームの操作」レッスンは無料ですか?

はい。「ファイルシステムとストリームの操作」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Node.js Backend Development Bootcampコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Node.js Backend Development Bootcampコースには全4レッスンが含まれています。

「ファイルシステムとストリームの操作」で何を学びますか?

Node.jsのfsモジュールを使って、同期・非同期の両方でファイルを読み書きする方法を学びます。さらに、ストリームで大量のデータを効率的に処理する方法も身につけます。 ブラウザで直接実行するハンズオンコードでNode.js Backend Development Bootcampを演習し、24時間対応の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に戻る