使用 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() 這三個方法都會在返回資料之前將檔案的全部內容讀入記憶體。

這意味著大檔案將對您的記憶體消耗和程式的執行速度產生重大影響。

在這種情況下,更好的選擇是使用流來讀取檔案內容。

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 分鐘
作者
貢獻
編輯此頁面