使用 Node.js 读取文件

¥Reading files with Node.js

在 Node.js 中读取文件的最简单方法是使用 fs.readFile() 方法,向其传递文件路径、编码和将使用文件数据(和错误)调用的回调函数:

¥The simplest way to read a file in Node.js is to use the fs.readFile() method, passing it the file path, encoding and a callback function that will be called with the file data (and the error):

const  = ('node:fs');

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

或者,你可以使用同步版本 fs.readFileSync()

¥Alternatively, you can use the synchronous version fs.readFileSync():

const  = ('node:fs');

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

你还可以使用 fs/promises 模块提供的基于 promise 的 fsPromises.readFile() 方法:

¥You can also use the promise-based fsPromises.readFile() method offered by the fs/promises module:

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

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

fs.readFile()fs.readFileSync()fsPromises.readFile() 三个都在返回数据之前读取内存中文件的全部内容。

¥All three of fs.readFile(), fs.readFileSync() and fsPromises.readFile() read the full content of the file in memory before returning the data.

这意味着大文件将对内存消耗和程序执行速度产生重大影响。

¥This means that big files are going to have a major impact on your memory consumption and speed of execution of the program.

在这种情况下,更好的选择是使用流读取文件内容。

¥In this case, a better option is to read the file content using streams.

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 (!. || !.) {
    // consuming the response body is mandatory: https://undici.nodejs.org/#/?id=garbage-collection
    await .?.();
    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}`);
}
阅读时间
3 min