Skip to content

Instantly share code, notes, and snippets.

@railson-ferreira
Created January 3, 2024 13:37
Show Gist options
  • Select an option

  • Save railson-ferreira/b212a14984126323ee756272771086ad to your computer and use it in GitHub Desktop.

Select an option

Save railson-ferreira/b212a14984126323ee756272771086ad to your computer and use it in GitHub Desktop.
Different Ways to implement read file in node (Async and nonAsync)
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