コンテンツにスキップ

fs

Since v8.0.75

fsモジュールは、JSHアプリケーション用にNode.js互換の同期ファイルシステムAPIを提供します。

readFile()

ファイルを読み取り、文字列(既定値:utf8)またはバイト配列で返します。

構文
readFile(path[, options])
使用例
1
2
3
const fs = require('fs');
const content = fs.readFile('/lib/fs.js', 'utf8');
console.println(content.length);

writeFile()

ファイルにデータを書き込みます。ファイルがなければ作成し、あれば上書きします。

構文
writeFile(path, data[, options])
使用例
1
2
const fs = require('fs');
fs.writeFile('/work/test.txt', 'Hello', 'utf8');

appendFile()

ファイルの末尾にデータを追加します。ファイルがなければ作成します。

構文
appendFile(path, data[, options])
使用例
1
2
3
const fs = require('fs');
fs.writeFile('/work/append.txt', 'Line 1\n', 'utf8');
fs.appendFile('/work/append.txt', 'Line 2\n', 'utf8');

countLines()

改行を基準に、ファイルの行数を数えます。

構文
countLines(path)
使用例
1
2
const fs = require('fs');
console.println(fs.countLines('/work/append.txt'));

exists()

ファイルまたはディレクトリが存在するかどうかを、trueまたはfalseで返します。

構文
exists(path)
使用例
1
2
3
const fs = require('fs');
console.println(fs.exists('/work/test.txt'));
console.println(fs.exists('/work/not-found.txt'));

stat()

ファイルまたはディレクトリのメタデータを返します。

構文
stat(path)
返されるフィールド
  • name, size, mode, mtime, atime, ctime, birthtime
  • isFile(), isDirectory(), isSymbolicLink()
  • isBlockDevice(), isCharacterDevice(), isFIFO(), isSocket()
使用例
1
2
3
4
const fs = require('fs');
const st = fs.stat('/work/test.txt');
console.println(st.isFile(), st.size);
console.println(st.name);

lstat()

ファイルのメタデータを返します。現在の実装では、stat()と同じ動作です。

構文
lstat(path)

readdir()

ディレクトリエントリを読み取ります。

  • 既定値:string[]を返す
  • withFileTypes: true: nameと型判定メソッドを持つエントリオブジェクトを返す
  • recursive: true: サブディレクトリを含めて再帰的に返す

現在のランタイムのディレクトリ一覧には、...が含まれます。

構文
readdir(path[, options])
使用例
1
2
3
4
const fs = require('fs');
const names = fs.readdir('/lib');
const entries = fs.readdir('/lib', { withFileTypes: true });
console.println(names.length, entries.length);

mkdir()

ディレクトリを作成します。再帰的な作成オプションに対応しています。

構文
mkdir(path[, options])
使用例
1
2
const fs = require('fs');
fs.mkdir('/work/a/b/c', { recursive: true });

rmdir()

ディレクトリを削除します。{ recursive: true }を指定すると、子エントリを先に削除します。

構文
rmdir(path[, options])

rm()

ファイルまたはディレクトリを削除します。

  • ディレクトリの削除には、内部でrmdir()を使用します。
  • force: trueを指定すると、エラーを無視します。
構文
rm(path[, options])

unlink()

ファイルを削除します。

構文
unlink(path)

rename()

同じマウント済みファイルシステム内で、ファイル・ディレクトリの名前を変更するか移動します。

構文
rename(oldPath, newPath)

copyFile()

単一ファイルをコピーします。

COPYFILE_EXCLフラグを指定すると、対象ファイルが存在する場合は失敗します。

構文
copyFile(src, dest[, flags])

cp()

ファイルまたはディレクトリをコピーします。

ディレクトリをコピーするには、{ recursive: true }が必要です。

構文
cp(src, dest[, options])

symlink()

シンボリックリンクを作成します。

構文
symlink(target, path)

readlink()

シンボリックリンクのリンク先パスを読み取ります。

構文
readlink(path)

realpath()

シンボリックリンクを解決した実際のパスを返します。

構文
realpath(path)

access()

パスにアクセスできるかどうかを確認します。

  • パスが存在しない場合は、ENOENT例外を発生させます。
  • モード定数F_OKR_OKW_OKX_OKに対応しています。
構文
access(path[, mode])

truncate()

ファイルの内容を切り詰めます。

  • 長さを省略すると、0に切り詰めます。
  • 長さを指定すると、先頭のlenバイトだけを保持します。
構文
truncate(path[, len])

open()

ファイルを開き、数値のファイルディスクリプターを返します。

文字列フラグrr+ww+aa+wxwx+axax+に対応しています。

構文
open(path, flags[, mode])

close()

ファイルディスクリプターを閉じます。

構文
close(fd)

read()

ファイルディスクリプターからバッファーにデータを読み取ります。

構文
read(fd, buffer, offset, length[, position])

write()

文字列またはバッファーのデータを、ファイルディスクリプターに書き込みます。

構文
write(fd, buffer, offset, length[, position])

fstat()

ファイルディスクリプターに対応するメタデータを返します。

構文
fstat(fd)

fchmod(), fchown()

ファイルディスクリプターでモード・所有者を変更します。

構文
fchmod(fd, mode)
fchown(fd, uid, gid)

fsync(), fdatasync()

保留中のファイルデータをストレージに同期します。

現在のfdatasync()は、fsync()と同じ動作です。

構文
fsync(fd)
fdatasync(fd)

chmod(), chown()

パスでモード・所有者を変更します。

現在のランタイム実装では、Windowsのchmodchownは何も処理しない互換動作(no-op)です。

構文
chmod(path, mode)
chown(path, uid, gid)

createReadStream(), createWriteStream()

EventEmitter方式の使用と互換性のある、ストリームオブジェクトを作成します。

構文
createReadStream(path[, options])
createWriteStream(path[, options])
使用例
1
2
3
4
const fs = require('fs');
const rs = fs.createReadStream('/work/in.txt', { encoding: 'utf8' });
const ws = fs.createWriteStream('/work/out.txt', { encoding: 'utf8' });
rs.pipe(ws);

platform(), arch()

ランタイムのプラットフォームとアーキテクチャの文字列を返します。

構文
platform()
arch()
使用例
1
2
3
const fs = require('fs');
console.println(fs.platform());
console.println(fs.arch());

constants

アクセス、コピー、ファイルを開く操作のフラグを含む定数オブジェクトです。

主なフィールド
  • アクセス: F_OK, R_OK, W_OK, X_OK
  • コピー: COPYFILE_EXCL, COPYFILE_FICLONE, COPYFILE_FICLONE_FORCE
  • ファイルを開く操作: O_RDONLY, O_WRONLY, O_RDWR, O_CREAT, O_EXCL, O_TRUNC, O_APPEND
使用例
1
2
const fs = require('fs');
fs.access('/work/test.txt', fs.constants.F_OK);

別名

読みやすさのため、このドキュメントではSyncのない名前でAPIを紹介します。

Node.jsとの互換性のため、Sync接尾辞を持つ別名も提供します。

例: readFileSync, writeFileSync, appendFileSync, readdirSync, mkdirSync, rmSync, statSync, openSync, closeSync, readSync, writeSync, fstatSync, fsyncSync, fdatasyncSync.

使用例

例1:JSONファイルの読み取りと解析

1
2
3
4
5
6
7
8
9
const fs = require('fs');

try {
	const content = fs.readFile('/path/to/config.json', 'utf8');
	const config = JSON.parse(content);
	console.println('Config loaded:', config);
} catch (e) {
	console.println('Error reading config:', e);
}

例2:ログファイルの書き込み

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const fs = require('fs');

function log(message) {
	const timestamp = new Date().toISOString();
	const logEntry = `[${timestamp}] ${message}\n`;
	fs.appendFile('/tmp/app.log', logEntry, 'utf8');
}

log('Application started');
log('Processing request');

例3:ディレクトリツリーの走査

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
const fs = require('fs');

function walkDir(dir, callback, indent = '') {
	const entries = fs.readdir(dir, { withFileTypes: true });

	entries.forEach(entry => {
		const fullPath = dir + '/' + entry.name;

		if (entry.isDirectory()) {
			console.println(indent + '[DIR] ' + entry.name);
			walkDir(fullPath, callback, indent + '  ');
		} else {
			console.println(indent + entry.name);
			callback(fullPath);
		}
	});
}

walkDir('/tmp', (file) => {
	// 各ファイルを処理
});

例4:ファイルのバックアップ

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
const fs = require('fs');

function backupFile(path) {
	if (!fs.exists(path)) {
		throw new Error('File does not exist');
	}

	const timestamp = Date.now();
	const backupPath = path + '.backup.' + timestamp;

	fs.copyFile(path, backupPath);
	console.println('Backup created:', backupPath);

	return backupPath;
}

backupFile('/tmp/important.txt');

例5:安全なファイル書き込み

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const fs = require('fs');

function safeWriteFile(path, data) {
	const tempPath = path + '.tmp';

	try {
		// 先に一時ファイルに書き込み
		fs.writeFile(tempPath, data, 'utf8');

		// 成功した場合は対象の名前に変更
		fs.rename(tempPath, path);

		console.println('File written safely');
	} catch (e) {
		// 一時ファイルがあれば削除
		if (fs.exists(tempPath)) {
			fs.unlink(tempPath);
		}
		throw e;
	}
}

safeWriteFile('/tmp/data.txt', 'Important data');
最終更新日