Created
January 3, 2024 13:37
-
-
Save railson-ferreira/b212a14984126323ee756272771086ad to your computer and use it in GitHub Desktop.
Different Ways to implement read file in node (Async and nonAsync)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const fs = require("fs"); | |
| const fsPromises = require("fs").promises; | |
| async function main() { | |
| // Sync | |
| const fileBuff = fs.readFileSync("file.txt"); | |
| const bArr = Uint8Array.from(fileBuff); | |
| // Async (EventLoop) | |
| const fileBuff2 = await fsPromises.readFile("file.txt"); | |
| // Async (EventLoop) but reinventing the wheel | |
| const fileBuff3 = await readFileAsync("file.txt"); | |
| // Async Conventional Way | |
| fs.readFile("file.txt", (err: any, data: Buffer) => { | |
| if (err) { | |
| console.error(err); | |
| } else { | |
| onFileReadSuccessfully(data); | |
| } | |
| }); | |
| } | |
| function onFileReadSuccessfully(buff: Buffer){ | |
| setState(Uint8Array.from(buff)) | |
| } | |
| async function readFileAsync(path: String) { | |
| return new Promise<Buffer>((resolve, reject) => { | |
| fs.readFile(path, (err: any, data: Buffer) => { | |
| if (err) { | |
| reject(err); | |
| } else { | |
| resolve(data); | |
| } | |
| }); | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment