fs、fs-extra、graceful-fs、memfs は、Node.js 環境におけるファイルシステム操作を支える重要なライブラリ群です。fs は Node.js コアに組み込まれた標準モジュールで、OS のファイルシステムを直接操作する基礎となります。fs-extra はこの fs を拡張し、ディレクトリの再帰的削除や JSON ファイルの読み書きなど、実務で頻繁に必要な機能を追加した上位互換ライブラリです。graceful-fs は、ファイルディスクリプタの枯渇や、Windows 環境特有のファイルロック問題に対して自動リトライ機構を提供し、アプリケーションの堅牢性を高めます。一方、memfs はメモリ上に仮想ファイルシステムを構築するライブラリであり、ディスク I/O を伴わない高速なテスト環境や、ブラウザ内でのファイル操作シミュレーションに不可欠なツールです。これらを適切に使い分けることは、パフォーマンス、信頼性、そしてテスト容易性に直結します。
Node.js アプリケーション開発において、ファイルシステムの扱いは避けて通れない課題です。データ永続化、設定ファイルの読み込み、ビルドプロセス、そしてテスト環境の構築など、あらゆる局面でファイル操作が必要になります。しかし、一口に「ファイル操作」と言っても、その目的によって最適なライブラリは全く異なります。
ここでは、Node.js エコシステムで最も重要な 4 つのパッケージ — fs、fs-extra、graceful-fs、memfs — を比較し、それぞれの役割と適切な使い分け方を技術的な観点から解説します。
fs vs fs-extraまず、Node.js の標準モジュールである fs と、それを拡張した fs-extra の関係性から理解しましょう。
fs は Node.js に最初から組み込まれているコアモジュールです。
// fs: 標準モジュール
const fs = require('fs');
const path = require('path');
// ディレクトリを再帰的に削除する際の従来型の記述(例)
function removeDirectory(dirPath) {
if (fs.existsSync(dirPath)) {
fs.readdirSync(dirPath).forEach((file) => {
const curPath = path.join(dirPath, file);
if (fs.lstatSync(curPath).isDirectory()) {
removeDirectory(curPath); // 再帰呼び出し
} else {
fs.unlinkSync(curPath); // ファイル削除
}
});
fs.rmdirSync(dirPath);
}
}
fs-extra は、この fs の機能を補完するために作られたライブラリです。
fs のすべてのメソッドを含みつつ、remove、copy、move、readJson などの便利な機能を追加しています。// fs-extra: 拡張ライブラリ
const fse = require('fs-extra');
// ディレクトリを再帰的に削除(ワンライナー)
await fse.remove('/tmp/my-dir');
// JSON ファイルの読み書きも簡単
const config = await fse.readJson('./config.json');
await fse.writeJson('./output.json', { status: 'ok' });
graceful-fs の役割大量のファイルを扱うツールや、長時間稼働するサーバーアプリケーションでは、予期せぬエラーに直面することがあります。特に「ファイルディスクリプタの枯渇(EMFILE エラー)」や、Windows 環境での「ファイルロック(EBUSY エラー)」は致命的になり得ます。
graceful-fs は、これらの問題に対処するためのパッチライブラリです。
fs モジュールをラップし、エラーが発生した際に自動的にリトライを行います。// graceful-fs: 耐障害性の向上
const gracefulFs = require('graceful-fs');
// fs モジュールの代わりにこれを読み込むだけで、全局的にリトライ機構が有効になる
gracefulFs.gracefulify(require('fs'));
// これ以降の fs 操作(あるいは fs-extra などの内部で使用される fs)は
// エラー時に自動リトライを試みるようになる
const data = gracefulFs.readFileSync('./large-file.txt');
注意すべき点として、fs-extra は内部で graceful-fs を依存関係として持っているため、fs-extra を使用しているだけで恩恵を受けられる場合があります。しかし、より明示的な制御が必要な場合や、純粋な fs を使いつつ耐障害性だけを加えたい場合には、直接 graceful-fs を使用します。
memfs の独自性他の 3 つが「実際のディスク」を操作するのに対し、memfs は全く異なるアプローチを取ります。これはメモリ上に仮想ファイルシステムを構築するライブラリです。
fs モジュールが存在しない場所でも、Node.js のファイル操作 API をシミュレートできます。// memfs: 仮想ファイルシステム
const { Volume } = require('memfs');
const { createFsFromVolume } = require('memfs');
// メモリ上にボリュームを作成
const vol = Volume.fromJSON({
'/hello.txt': 'Hello World',
'/data/config.json': JSON.stringify({ env: 'test' })
});
// 通常の fs と同じインターフェースを持つファイルシステムインスタンスを生成
const mfs = createFsFromVolume(vol);
// ディスクへのアクセスなしに読み込みが可能
const content = mfs.readFileSync('/hello.txt', 'utf8');
console.log(content); // "Hello World"
実際の開発現場では、これらのライブラリを単独で使うだけでなく、組み合わせて使用することが一般的です。
ビルドツールでは、大量のファイルを処理し、かつ処理の確実性が求められます。
fs-extra + graceful-fsfs-extra で記述を簡潔にしつつ、graceful-fs で OS リソースの競合や制限に対処します。// ビルドスクリプトの例
const fse = require('fs-extra');
const gracefulFs = require('graceful-fs');
// 内部で fs を使うライブラリに対してパッチを当てる
gracefulFs.gracefulify(require('fs'));
async function build() {
await fse.emptyDir('./dist'); // ディレクトリを空にする
await fse.copy('./src', './dist'); // コピー
// エラー時に自動リトライされ、ビルドが中断しにくくなる
}
ライブラリのテストにおいて、実際のファイルを生成・削除するのは遅く、危険です。
memfs// Jest などのテスト環境での例
const { Volume } = require('memfs');
const { createFsFromVolume } = require('memfs');
test('ファイル処理ロジックの検証', () => {
const vol = Volume.fromJSON({ '/input.txt': 'data' });
const mfs = createFsFromVolume(vol);
// 実際のディスクを使わずに処理ロジックをテスト
const result = myFileProcessingFunction(mfs, '/input.txt');
expect(result).toBe('processed data');
// テスト終了後、ディスクのクリーンアップは不要
});
小さなスクリプトや、依存関係を増やしたくないCLI ツールの一部として。
fs (標準)// 単純な設定読み込み
const fs = require('fs');
const path = require('path');
const configPath = path.join(__dirname, 'config.json');
if (fs.existsSync(configPath)) {
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
// 処理 continued...
}
| 特徴 | fs (標準) | fs-extra | graceful-fs | memfs |
|---|---|---|---|---|
| 主な目的 | 基本操作 | 機能拡張・簡略化 | エラー耐性向上 | 仮想化・テスト |
| ディスク I/O | あり | あり | あり | なし (メモリ上) |
| 再帰的削除 | 手動 or 新規 API | remove() で簡単 | 手動 | remove() で簡単 |
| JSON 操作 | 手動 (JSON.parse) | readJson() 等 | 手動 | readJson() 等 |
| リトライ機構 | なし | あり (内部依存) | あり (主機能) | なし |
| ブラウザ対応 | ❌ (Node.js のみ) | ❌ (Node.js のみ) | ❌ (Node.js のみ) | ✅ (ポリフィル可能) |
プロジェクトの規模や目的に応じて、以下の方針で選定することをお勧めします。
fs-extra を採用してください。コードの可読性が向上し、メンテナンスコストが下がります。これには graceful-fs の恩恵も間接的に含まれることが多いです。graceful-fs を導入し、fs モジュール全体をラップすることを検討してください。memfs を活用してください。ディスク I/O を排除することで、テストの信頼性と速度が飛躍的に向上します。fs のみを使用し、依存関係を断つ判断も賢明です。これらのツールは互いに排他的なものではなく、状況に応じて組み合わせることで、より強力で保守性の高い Node.js アプリケーションを構築することができます。それぞれの特性を理解し、適切に使い分けることが、プロフェッショナルなエンジニアリングの鍵となります。
実務開発において、ディレクトリの再帰的な操作(作成・削除)や、JSON ファイルの簡易な読み書きを頻繁に行う場合に首选されます。fs モジュールの完全な上位互換であるため、require('fs') を require('fs-extra') に置き換えるだけで、追加のメソッドを利用でき、ボイラープレートコードを大幅に削減できます。
Node.js の標準機能だけで要件が満たせる場合や、依存パッケージ数を極限まで減らしたい基盤ライブラリを開発する際に選択します。追加のインストールが不要で、すべての Node.js 環境で確実に動作するため、単純なファイル読み書きや、他のラッパーライブラリの基盤として使用するのに適しています。
大量のファイルを同時に処理する際や、Windows 環境でファイルの競合(ロック)が発生しやすいツールを開発する際に採用します。fs モジュールをラップして使用することで、EMFILE エラー(ファイルディスクリプタ枯渇)や EBUSY エラーに対して自動的にリトライを行い、アプリケーションのクラッシュを防ぎます。
ユニットテストや統合テストにおいて、実際のディスクアクセスを避けたい場合、あるいはブラウザ環境で Node.js のファイルシステム API をエミュレートする必要がある場合に必須です。メモリ上で完結するため処理が非常に高速であり、テスト実行後のクリーンアップ作業も不要になるため、CI/CD パイプラインの高速化に貢献します。
fs-extra adds file system methods that aren't included in the native fs module and adds promise support to the fs methods. It also uses graceful-fs to prevent EMFILE errors. It should be a drop in replacement for fs.
I got tired of including mkdirp, rimraf, and ncp in most of my projects.
npm install fs-extra
fs-extra is a drop in replacement for native fs. All methods in fs are attached to fs-extra. All fs methods return promises if the callback isn't passed.
You don't ever need to include the original fs module again:
const fs = require('fs') // this is no longer necessary
you can now do this:
const fs = require('fs-extra')
or if you prefer to make it clear that you're using fs-extra and not fs, you may want
to name your fs variable fse like so:
const fse = require('fs-extra')
you can also keep both, but it's redundant:
const fs = require('fs')
const fse = require('fs-extra')
NOTE: The deprecated constants fs.F_OK, fs.R_OK, fs.W_OK, & fs.X_OK are not exported on Node.js v24.0.0+; please use their fs.constants equivalents.
There is also an fs-extra/esm import, that supports both default and named exports. However, note that fs methods are not included in fs-extra/esm; you still need to import fs and/or fs/promises separately:
import { readFileSync } from 'fs'
import { readFile } from 'fs/promises'
import { outputFile, outputFileSync } from 'fs-extra/esm'
Default exports are supported:
import fs from 'fs'
import fse from 'fs-extra/esm'
// fse.readFileSync is not a function; must use fs.readFileSync
but you probably want to just use regular fs-extra instead of fs-extra/esm for default exports:
import fs from 'fs-extra'
// both fs and fs-extra methods are defined
Most methods are async by default. All async methods will return a promise if the callback isn't passed.
Sync methods on the other hand will throw if an error occurs.
Also Async/Await will throw an error if one occurs.
Example:
const fs = require('fs-extra')
// Async with promises:
fs.copy('/tmp/myfile', '/tmp/mynewfile')
.then(() => console.log('success!'))
.catch(err => console.error(err))
// Async with callbacks:
fs.copy('/tmp/myfile', '/tmp/mynewfile', err => {
if (err) return console.error(err)
console.log('success!')
})
// Sync:
try {
fs.copySync('/tmp/myfile', '/tmp/mynewfile')
console.log('success!')
} catch (err) {
console.error(err)
}
// Async/Await:
async function copyFiles () {
try {
await fs.copy('/tmp/myfile', '/tmp/mynewfile')
console.log('success!')
} catch (err) {
console.error(err)
}
}
copyFiles()
NOTE: You can still use the native Node.js methods. They are promisified and copied over to fs-extra. See notes on fs.read(), fs.write(), & fs.writev()
walk() and walkSync()?They were removed from fs-extra in v2.0.0. If you need the functionality, walk and walkSync are available as separate packages, klaw and klaw-sync.
fse-cli allows you to run fs-extra from a console or from npm scripts.
If you like TypeScript, you can use fs-extra with it: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/fs-extra
If you want to watch for changes to files or directories, then you should use chokidar.
fs-filesystem allows you to read the state of the filesystem of the host on which it is run. It returns information about both the devices and the partitions (volumes) of the system.
Wanna hack on fs-extra? Great! Your help is needed! fs-extra is one of the most depended upon Node.js packages. This project
uses JavaScript Standard Style - if the name or style choices bother you,
you're gonna have to get over it :) If standard is good enough for npm, it's good enough for fs-extra.
What's needed?
Note: If you make any big changes, you should definitely file an issue for discussion first.
fs-extra contains hundreds of tests.
npm run lint: runs the linter (standard)npm run unit: runs the unit testsnpm run unit-esm: runs tests for fs-extra/esm exportsnpm test: runs the linter and all testsWhen running unit tests, set the environment variable CROSS_DEVICE_PATH to the absolute path of an empty directory on another device (like a thumb drive) to enable cross-device move tests.
If you run the tests on the Windows and receive a lot of symbolic link EPERM permission errors, it's
because on Windows you need elevated privilege to create symbolic links. You can add this to your Windows's
account by following the instructions here: http://superuser.com/questions/104845/permission-to-make-symbolic-links-in-windows-7
However, I didn't have much luck doing this.
Since I develop on Mac OS X, I use VMWare Fusion for Windows testing. I create a shared folder that I map to a drive on Windows.
I open the Node.js command prompt and run as Administrator. I then map the network drive running the following command:
net use z: "\\vmware-host\Shared Folders"
I can then navigate to my fs-extra directory and run the tests.
I put a lot of thought into the naming of these functions. Inspired by @coolaj86's request. So he deserves much of the credit for raising the issue. See discussion(s) here:
First, I believe that in as many cases as possible, the Node.js naming schemes should be chosen. However, there are problems with the Node.js own naming schemes.
For example, fs.readFile() and fs.readdir(): the F is capitalized in File and the d is not capitalized in dir. Perhaps a bit pedantic, but they should still be consistent. Also, Node.js has chosen a lot of POSIX naming schemes, which I believe is great. See: fs.mkdir(), fs.rmdir(), fs.chown(), etc.
We have a dilemma though. How do you consistently name methods that perform the following POSIX commands: cp, cp -r, mkdir -p, and rm -rf?
My perspective: when in doubt, err on the side of simplicity. A directory is just a hierarchical grouping of directories and files. Consider that for a moment. So when you want to copy it or remove it, in most cases you'll want to copy or remove all of its contents. When you want to create a directory, if the directory that it's suppose to be contained in does not exist, then in most cases you'll want to create that too.
So, if you want to remove a file or a directory regardless of whether it has contents, just call fs.remove(path). If you want to copy a file or a directory whether it has contents, just call fs.copy(source, destination). If you want to create a directory regardless of whether its parent directories exist, just call fs.mkdirs(path) or fs.mkdirp(path).
fs-extra wouldn't be possible without using the modules from the following authors:
Licensed under MIT
Copyright (c) 2011-2024 JP Richardson