i am trying to run a async read write in nodejs and trying to measure execution time by using perfomance.now . But inside the call back function, performance.now gives me undefined.
const { performance } = require("perf_hooks");
var st1 = performance.now();
console.log("start");
var st2, st3, st4, st5;
const { readFile, writeFile } = require("fs");
console.log("middle");
readFile("./content/first.txt", "utf-8", (err, result) => {
if (err) {
console.log(err);
return;
}
const first = result;
st2 = performance.now();
readFile("./content/second.txt", "utf-8", (err, result) => {
if (err) {
console.log(err);
return;
}
const second = result;
st3 = performance.now();
writeFile(
"./content/result-async.text",
`Here is the result : ${first}: ${second}`,
(err, result) => {
if (err) {
console.log(err);
return;
}
console.log(result);
console.log("after result");
st4 = performance.now();
}
);
});
});
console.log("end");
console.log("after end");
st5 = performance.now();
console.log(`st1=${st1},st2=${st2},st3=${st3},st4=${st4},st5=${st5}`);
below was the result for the above
start
middle
end
after end
st1=50.264651000499725,st2=undefined,st3=undefined,st4=undefined,st5=56.36346299946308
undefined
after result
i cannot understand the reason for st2,st3 and st4 being undefined???
i tried searching for reasons on mdn docs for the same, but there is no mention for use case in async environment. want to knoe what could be the reason for this.