使用 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 分钟
作者
贡献
编辑此页面