Skip to content

Instantly share code, notes, and snippets.

@decasteljau
Created December 1, 2018 19:44
Show Gist options
  • Select an option

  • Save decasteljau/dc4f5d071dc66ae1ece8eefcb3c075fe to your computer and use it in GitHub Desktop.

Select an option

Save decasteljau/dc4f5d071dc66ae1ece8eefcb3c075fe to your computer and use it in GitHub Desktop.
import * as fs from 'fs';
import * as util from 'util';
const fsp = fs.promises;
function myRead(callback: (e: Error, result: string) => void) {
fs.readFile("C:/temp/data.txt", (e, buffer) => { callback(e, buffer.toString()) });
}
function myRead2(): Promise<string> {
return new Promise<string>((resolve, reject) => {
fs.readFile("C:/temp/data.txt", (e, buffer) => {
if (e) {
return reject(e);
}
resolve(buffer.toString());
});
});
}
async function myRead3() : Promise<string> {
return (await fsp.readFile("C:/temp/data.txt")).toString();
}
async function main() {
const buffer1 = await fsp.readFile("C:/temp/data.txt");
console.log(buffer1.toString());
const buffer2 = await util.promisify(fs.readFile)("C:/temp/data.txt");
console.log(buffer2.toString());
const res3 = await util.promisify(myRead)();
console.log(res3);
const res4 = await myRead2();
console.log(res4);
const res5 = await myRead3();
console.log(res5);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment