@@ -88,3 +88,48 @@ All three of `fs.readFile()`, `fs.readFileSync()` and `fsPromises.readFile()` re
8888This means that big files are going to have a major impact on your memory consumption and speed of execution of the program.
8989
9090In this case, a better option is to read the file content using streams.
91+
92+ ``` mjs
93+ import fs from ' fs' ;
94+ import path from ' path' ;
95+
96+ const fileUrl = ' https://www.gutenberg.org/files/2701/2701-0.txt' ;
97+ const outputFilePath = path .join (process .cwd (), ' mobey.md' );
98+ import { pipeline } from ' node:stream/promises' ;
99+
100+ async function downloadFile (url , outoutPath ) {
101+ const response = await fetch (url);
102+
103+ if (! response .ok || ! response .body ) {
104+ throw new Error (` Failed to fetch ${ url} . Status: ${ response .status } ` );
105+ }
106+
107+ const fileStream = fs .createWriteStream (outoutPath);
108+ console .log (` Downloading file from ${ url} to ${ outoutPath} ` );
109+
110+ await pipeline (response .body , fileStream);
111+ console .log (' File downloaded successfully' );
112+ }
113+
114+ async function readFile (filePath ) {
115+ const readStream = createReadStream (filePath, { encoding: ' utf8' });
116+
117+ try {
118+ for await (const chunk of readStream ) {
119+ console .log (' --- File chunk start ---' );
120+ console .log (chunk);
121+ console .log (' --- File chunk end ---' );
122+ }
123+ console .log (' Finished reading the file.' );
124+ } catch (error) {
125+ console .error (` Error reading file: ${ error .message } ` );
126+ }
127+ }
128+
129+ try {
130+ await downloadFile (fileUrl, outputFilePath);
131+ await readFile (outputFilePath);
132+ } catch (error) {
133+ console .error (` Error: ${ error .message } ` );
134+ }
135+ ```
0 commit comments