Reading files with Node.js

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 module "node:fs"fs = 
var require: NodeJS.Require
(id: string) => any
require
('node:fs');
module "node:fs"fs.
function readFile(path: fs.PathOrFileDescriptor, options: ({
    encoding: BufferEncoding;
    flag?: string | undefined;
} & EventEmitter<T extends EventMap<T> = DefaultEventMap>.Abortable) | BufferEncoding, callback: (err: NodeJS.ErrnoException | null, data: string) => void): void (+3 overloads)
readFile
('/Users/joe/test.txt', 'utf8', (err: NodeJS.ErrnoException | nullerr, data: stringdata) => {
if (err: NodeJS.ErrnoException | nullerr) { var console: Consoleconsole.Console.error(message?: any, ...optionalParams: any[]): void (+1 overload)error(err: NodeJS.ErrnoExceptionerr); return; } var console: Consoleconsole.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)log(data: stringdata); });

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

const module "node:fs"fs = 
var require: NodeJS.Require
(id: string) => any
require
('node:fs');
try { const const data: stringdata = module "node:fs"fs.
function readFileSync(path: fs.PathOrFileDescriptor, options: {
    encoding: BufferEncoding;
    flag?: string | undefined;
} | BufferEncoding): string (+2 overloads)
readFileSync
('/Users/joe/test.txt', 'utf8');
var console: Consoleconsole.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)log(const data: stringdata); } catch (var err: unknownerr) { var console: Consoleconsole.Console.error(message?: any, ...optionalParams: any[]): void (+1 overload)error(var err: unknownerr); }

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

const module "node:fs/promises"fs = 
var require: NodeJS.Require
(id: string) => any
require
('node:fs/promises');
async function function example(): Promise<void>example() { try { const const data: stringdata = await module "node:fs/promises"fs.
function readFile(path: PathLike | fs.FileHandle, options: ({
    encoding: BufferEncoding;
    flag?: OpenMode | undefined;
} & EventEmitter<T extends EventMap<T> = DefaultEventMap>.Abortable) | BufferEncoding): Promise<string> (+2 overloads)
readFile
('/Users/joe/test.txt', { encoding: BufferEncodingencoding: 'utf8' });
var console: Consoleconsole.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)log(const data: stringdata); } catch (function (local var) err: unknownerr) { var console: Consoleconsole.Console.error(message?: any, ...optionalParams: any[]): void (+1 overload)error(function (local var) err: unknownerr); } } function example(): Promise<void>example();

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 module "fs"fs from 'fs';
import { function pipeline<A extends Stream.PipelineSource<any>, B extends Stream.PipelineDestination<A, any>>(source: A, destination: B, options?: Stream.PipelineOptions): Stream.PipelinePromise<B> (+6 overloads)pipeline } from 'node:stream/promises';
import const path: path.PlatformPathpath from 'path';

const const fileUrl: "https://www.gutenberg.org/files/2701/2701-0.txt"fileUrl = 'https://www.gutenberg.org/files/2701/2701-0.txt';
const const outputFilePath: stringoutputFilePath = const path: path.PlatformPathpath.path.PlatformPath.join(...paths: string[]): stringjoin(var process: NodeJS.Processprocess.NodeJS.Process.cwd(): stringcwd(), 'moby.md');

async function function downloadFile(url: any, outputPath: any): Promise<void>downloadFile(url: anyurl, outputPath: anyoutputPath) {
  const const response: Responseresponse = await function fetch(input: string | URL | globalThis.Request, init?: RequestInit): Promise<Response> (+1 overload)fetch(url: anyurl);

  if (!const response: Responseresponse.Response.ok: booleanok || !const response: Responseresponse.Body.body: ReadableStream<Uint8Array<ArrayBufferLike>> | nullbody) {
    throw new 
var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error
(`Failed to fetch ${url: anyurl}. Status: ${const response: Responseresponse.Response.status: numberstatus}`);
} const const fileStream: fs.WriteStreamfileStream = module "fs"fs.function createWriteStream(path: fs.PathLike, options?: BufferEncoding | WriteStreamOptions): fs.WriteStreamcreateWriteStream(outputPath: anyoutputPath); var console: Consoleconsole.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)log(`Downloading file from ${url: anyurl} to ${outputPath: anyoutputPath}`); await pipeline<ReadableStream<Uint8Array<ArrayBufferLike>>, fs.WriteStream>(source: ReadableStream<Uint8Array<ArrayBufferLike>>, destination: fs.WriteStream, options?: Stream.PipelineOptions): Promise<...> (+6 overloads)pipeline(const response: Responseresponse.Body.body: ReadableStream<Uint8Array<ArrayBufferLike>>body, const fileStream: fs.WriteStreamfileStream); var console: Consoleconsole.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)log('File downloaded successfully'); } async function function readFile(filePath: any): Promise<void>readFile(filePath: anyfilePath) { const const readStream: fs.ReadStreamreadStream = module "fs"fs.function createReadStream(path: fs.PathLike, options?: BufferEncoding | ReadStreamOptions): fs.ReadStreamcreateReadStream(filePath: anyfilePath, { StreamOptions.encoding?: BufferEncoding | undefinedencoding: 'utf8' }); try { for await (const const chunk: anychunk of const readStream: fs.ReadStreamreadStream) { var console: Consoleconsole.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)log('--- File chunk start ---'); var console: Consoleconsole.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)log(const chunk: anychunk); var console: Consoleconsole.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)log('--- File chunk end ---'); } var console: Consoleconsole.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)log('Finished reading the file.'); } catch (function (local var) error: unknownerror) { var console: Consoleconsole.Console.error(message?: any, ...optionalParams: any[]): void (+1 overload)error(`Error reading file: ${function (local var) error: unknownerror.message}`); } } try { await function downloadFile(url: any, outputPath: any): Promise<void>downloadFile(const fileUrl: "https://www.gutenberg.org/files/2701/2701-0.txt"fileUrl, const outputFilePath: stringoutputFilePath); await function readFile(filePath: any): Promise<void>readFile(const outputFilePath: stringoutputFilePath); } catch (var error: unknownerror) { var console: Consoleconsole.Console.error(message?: any, ...optionalParams: any[]): void (+1 overload)error(`Error: ${var error: unknownerror.message}`); }
Temps de Lecture
2 min
Auteurs
Contribuer
Éditer cette page