Node.js でファイルを読み込む

Node.js でファイルを読み込む最も簡単な方法は fs.readFile() メソッドを使うことです。このメソッドには、ファイルのパス、エンコーディング、そしてファイルデータ(とエラー)とともに呼び出されるコールバック関数を渡します。

const  = ('node:fs');

.('/Users/joe/test.txt', 'utf8', (, ) => {
  if () {
    .();
    return;
  }
  .();
});

あるいは、同期版の fs.readFileSync() を使うこともできます。

const  = ('node:fs');

try {
  const  = .('/Users/joe/test.txt', 'utf8');
  .();
} catch () {
  .();
}

fs/promises モジュールによって提供される、Promise ベースの fsPromises.readFile() メソッドも使用できます。

const  = ('node:fs/promises');

async function () {
  try {
    const  = await .('/Users/joe/test.txt', { : 'utf8' });
    .();
  } catch () {
    .();
  }
}
();

fs.readFile()fs.readFileSync()fsPromises.readFile() の 3 つはすべて、データを返す前にファイルの全内容をメモリに読み込みます。

これは、大きなファイルがメモリ消費とプログラムの実行速度に大きな影響を与えることを意味します。

この場合、より良い選択肢は、ストリームを使ってファイルの内容を読み込むことです。

import  from 'fs';
import {  } from 'node:stream/promises';
import  from 'path';

const  = 'https://www.gutenberg.org/files/2701/2701-0.txt';
const  = .(.(), 'moby.md');

async function (, ) {
  const  = await ();

  if (!. || !.) {
    throw new (`Failed to fetch ${}. Status: ${.}`);
  }

  const  = .();
  .(`Downloading file from ${} to ${}`);

  await (., );
  .('File downloaded successfully');
}

async function () {
  const  = .(, { : 'utf8' });

  try {
    for await (const  of ) {
      .('--- File chunk start ---');
      .();
      .('--- File chunk end ---');
    }
    .('Finished reading the file.');
  } catch () {
    .(`Error reading file: ${.message}`);
  }
}

try {
  await (, );
  await ();
} catch () {
  .(`Error: ${.message}`);
}
読了時間
2分
作成者
コントリビュート
このページを編集