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 fs
fs = require: any
require('node:fs');
import fs
fs.readFile('/Users/joe/test.txt', 'utf8', (err: any
err, data: any
data) => {
if (err: any
err) {
var console: Console
console.Console.error(...data: any[]): void
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static)error(err: any
err);
return;
}
var console: Console
console.Console.log(...data: any[]): void
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(data: any
data);
});
Alternatively, you can use the synchronous version fs.readFileSync()
:
const import fs
fs = require: any
require('node:fs');
try {
const const data: any
data = import fs
fs.readFileSync('/Users/joe/test.txt', 'utf8');
var console: Console
console.Console.log(...data: any[]): void
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(const data: any
data);
} catch (var err: unknown
err) {
var console: Console
console.Console.error(...data: any[]): void
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static)error(var err: unknown
err);
}
You can also use the promise-based fsPromises.readFile()
method offered by the fs/promises
module:
const import fs
fs = require: any
require('node:fs/promises');
async function function example(): Promise<void>
example() {
try {
const const data: any
data = await import fs
fs.readFile('/Users/joe/test.txt', { encoding: string
encoding: 'utf8' });
var console: Console
console.Console.log(...data: any[]): void
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(const data: any
data);
} catch (function (local var) err: unknown
err) {
var console: Console
console.Console.error(...data: any[]): void
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static)error(function (local var) err: unknown
err);
}
}
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 fs
fs from 'fs';
import { import pipeline
pipeline } from 'node:stream/promises';
import import path
path 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: any
outputFilePath = import path
path.join(process.cwd(), 'moby.md');
async function function downloadFile(url: any, outputPath: any): Promise<void>
downloadFile(url: any
url, outputPath: any
outputPath) {
const const response: Response
response = await function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch)fetch(url: any
url);
if (!const response: Response
response.Response.ok: boolean
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok)ok || !const response: Response
response.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: any
url}. Status: ${const response: Response
response.Response.status: number
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status)status}`);
}
const const fileStream: any
fileStream = import fs
fs.createWriteStream(outputPath: any
outputPath);
var console: Console
console.Console.log(...data: any[]): void
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(`Downloading file from ${url: any
url} to ${outputPath: any
outputPath}`);
await import pipeline
pipeline(const response: Response
response.Body.body: ReadableStream<Uint8Array<ArrayBufferLike>>
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body)body, const fileStream: any
fileStream);
var console: Console
console.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: any
filePath) {
const const readStream: any
readStream = import fs
fs.createReadStream(filePath: any
filePath, { encoding: string
encoding: 'utf8' });
try {
for await (const const chunk: any
chunk of const readStream: any
readStream) {
var console: Console
console.Console.log(...data: any[]): void
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log('--- File chunk start ---');
var console: Console
console.Console.log(...data: any[]): void
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(const chunk: any
chunk);
var console: Console
console.Console.log(...data: any[]): void
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log('--- File chunk end ---');
}
var console: Console
console.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: unknown
error) {
var console: Console
console.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: unknown
error.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: any
outputFilePath);
await function readFile(filePath: any): Promise<void>
readFile(const outputFilePath: any
outputFilePath);
} catch (var error: unknown
error) {
var console: Console
console.Console.error(...data: any[]): void
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static)error(`Error: ${var error: unknown
error.message}`);
}