I want to write a script that read a file and print some informations; the output of the code below is:
PRE runAsync
POST runAsync
POST asyncResult:
END
INSIDE FILE3 readFile callback function...
The script doesn't print the content of the file FILE3; where is the problem? I'm confusing about promise/async/await! I'm using nodejs and typescript.
import * as fs from "fs";
const FILE3 = "./sample3.txt";
async function readAsyncFile(FILE3: string): Promise<string> {
//const orWithVariable = function readPromise() {
let fileContent: string = "";
fs.readFile(FILE3, "utf8", (err, data) => {
console.log("INSIDE FILE3 readFile callback function...");
if (err) fileContent = "Error reading FILE3";
else fileContent = data;
});
return fileContent;
}
async function runAsync() {
let asyncResult: string = await readAsyncFile(FILE3);
console.log("POST asyncResult: " + asyncResult);
}
console.log("PRE runAsync");
runAsync().then(() => {
console.log("END");
});
console.log("POST runAsync");
The expected output should be:
PRE runAsync
POST runAsync
POST asyncResult:
--> here the content of FILE3 END
INSIDE FILE3 readFile callback function...
NOTE: I'm trying to understand promise/await/async with nodejs and typscript; can anybody tell me where to start? Good and simple tutorials with lots of examples? Thanks.