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 import fsfs = require: anyrequire('node:fs');
import fsfs.readFile('/Users/joe/test.txt', 'utf8', (err: anyerr, data: anydata) => {
if (err: anyerr) {
var console: Consoleconsole.Console.error(...data: any[]): void[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static)error(err: anyerr);
return;
}
var console: Consoleconsole.Console.log(...data: any[]): void[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(data: anydata);
});
Alternatively, you can use the synchronous version fs.readFileSync():
const import fsfs = require: anyrequire('node:fs');
try {
const const data: anydata = import fsfs.readFileSync('/Users/joe/test.txt', 'utf8');
var console: Consoleconsole.Console.log(...data: any[]): void[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(const data: anydata);
} catch (var err: unknownerr) {
var console: Consoleconsole.Console.error(...data: any[]): void[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static)error(var err: unknownerr);
}
You can also use the promise-based fsPromises.readFile() method offered by the fs/promises module:
const import fsfs = require: anyrequire('node:fs/promises');
async function function example(): Promise<void>example() {
try {
const const data: anydata = await import fsfs.readFile('/Users/joe/test.txt', { encoding: stringencoding: 'utf8' });
var console: Consoleconsole.Console.log(...data: any[]): void[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(const data: anydata);
} catch (function (local var) err: unknownerr) {
var console: Consoleconsole.Console.error(...data: any[]): void[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static)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 import fsfs from 'fs';
import { import pipelinepipeline } from 'node:stream/promises';
import import pathpath 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: anyoutputFilePath = import pathpath.join(process.cwd(), '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: RequestInfo | URL, init?: RequestInit): Promise<Response>[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch)fetch(url: anyurl);
if (!const response: Responseresponse.Response.ok: boolean[MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok)ok || !const response: Responseresponse.Body.body: ReadableStream<Uint8Array<ArrayBufferLike>> | null[MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body)body) {
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: number[MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status)status}`);
}
const const fileStream: anyfileStream = import fsfs.createWriteStream(outputPath: anyoutputPath);
var console: Consoleconsole.Console.log(...data: any[]): void[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(`Downloading file from ${url: anyurl} to ${outputPath: anyoutputPath}`);
await import pipelinepipeline(const response: Responseresponse.Body.body: ReadableStream<Uint8Array<ArrayBufferLike>>[MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body)body, const fileStream: anyfileStream);
var console: Consoleconsole.Console.log(...data: any[]): void[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log('File downloaded successfully');
}
async function function readFile(filePath: any): Promise<void>readFile(filePath: anyfilePath) {
const const readStream: anyreadStream = import fsfs.createReadStream(filePath: anyfilePath, { encoding: stringencoding: 'utf8' });
try {
for await (const const chunk: anychunk of const readStream: anyreadStream) {
var console: Consoleconsole.Console.log(...data: any[]): void[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log('--- File chunk start ---');
var console: Consoleconsole.Console.log(...data: any[]): void[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(const chunk: anychunk);
var console: Consoleconsole.Console.log(...data: any[]): void[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log('--- File chunk end ---');
}
var console: Consoleconsole.Console.log(...data: any[]): void[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log('Finished reading the file.');
} catch (function (local var) error: unknownerror) {
var console: Consoleconsole.Console.error(...data: any[]): void[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static)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: anyoutputFilePath);
await function readFile(filePath: any): Promise<void>readFile(const outputFilePath: anyoutputFilePath);
} catch (var error: unknownerror) {
var console: Consoleconsole.Console.error(...data: any[]): void[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static)error(`Error: ${var error: unknownerror.message}`);
}