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 | null
err, data: string
data) => {
if (err: NodeJS.ErrnoException | null
err) {
var console: Console
console.Console.error(message?: any, ...optionalParams: any[]): void (+1 overload)
error(err: NodeJS.ErrnoException
err);
return;
}
var console: Console
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
log(data: string
data);
});
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: string
data = 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: Console
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
log(const data: string
data);
} catch (var err: unknown
err) {
var console: Console
console.Console.error(message?: any, ...optionalParams: any[]): void (+1 overload)
error(var err: unknown
err);
}
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: string
data = 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: BufferEncoding
encoding: 'utf8' });
var console: Console
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
log(const data: string
data);
} catch (function (local var) err: unknown
err) {
var console: Console
console.Console.error(message?: any, ...optionalParams: any[]): void (+1 overload)
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 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.PlatformPath
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: string
outputFilePath = const path: path.PlatformPath
path.path.PlatformPath.join(...paths: string[]): string
join(var process: NodeJS.Process
process.NodeJS.Process.cwd(): string
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: string | URL | globalThis.Request, init?: RequestInit): Promise<Response> (+1 overload)
fetch(url: any
url);
if (!const response: Response
response.Response.ok: boolean
ok || !const response: Response
response.Body.body: ReadableStream<Uint8Array<ArrayBufferLike>> | null
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
status}`);
}
const const fileStream: fs.WriteStream
fileStream = module "fs"
fs.function createWriteStream(path: fs.PathLike, options?: BufferEncoding | WriteStreamOptions): fs.WriteStream
createWriteStream(outputPath: any
outputPath);
var console: Console
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
log(`Downloading file from ${url: any
url} to ${outputPath: any
outputPath}`);
await pipeline<ReadableStream<Uint8Array<ArrayBufferLike>>, fs.WriteStream>(source: ReadableStream<Uint8Array<ArrayBufferLike>>, destination: fs.WriteStream, options?: Stream.PipelineOptions): Promise<...> (+6 overloads)
pipeline(const response: Response
response.Body.body: ReadableStream<Uint8Array<ArrayBufferLike>>
body, const fileStream: fs.WriteStream
fileStream);
var console: Console
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
log('File downloaded successfully');
}
async function function readFile(filePath: any): Promise<void>
readFile(filePath: any
filePath) {
const const readStream: fs.ReadStream
readStream = module "fs"
fs.function createReadStream(path: fs.PathLike, options?: BufferEncoding | ReadStreamOptions): fs.ReadStream
createReadStream(filePath: any
filePath, { StreamOptions.encoding?: BufferEncoding | undefined
encoding: 'utf8' });
try {
for await (const const chunk: any
chunk of const readStream: fs.ReadStream
readStream) {
var console: Console
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
log('--- File chunk start ---');
var console: Console
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
log(const chunk: any
chunk);
var console: Console
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
log('--- File chunk end ---');
}
var console: Console
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
log('Finished reading the file.');
} catch (function (local var) error: unknown
error) {
var console: Console
console.Console.error(message?: any, ...optionalParams: any[]): void (+1 overload)
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: string
outputFilePath);
await function readFile(filePath: any): Promise<void>
readFile(const outputFilePath: string
outputFilePath);
} catch (var error: unknown
error) {
var console: Console
console.Console.error(message?: any, ...optionalParams: any[]): void (+1 overload)
error(`Error: ${var error: unknown
error.message}`);
}