Every day i m learning new things in javascript(nodejs) however one thing that's quite confusing for me is the concept of async-await.
Need a little help in managing the sequence of execution in below code. here's how it should execute I m writing a daily script which should read file value from local system ( file contains : last run date). put a new value in the file after it finishes reading the file(File should store current date).
fs = require('fs');
path = require('path');
let todaysDate = new Date();
async function checkPreviousRunDate() {
console.log("Step 1 : Today's Date: " + todaysDate.getDate());
filePath = path.join(__dirname, 'lastrundetail.txt');
var filedata;
await fs.readFile(filePath, {
encoding: 'utf-8'
}, function(err, data) {
if (!err) {
console.log('Step 2 :Last run was done on(MM/DD/YYYY): ' + data);
let lastrunDate = new Date(data);
const diffTime = Math.abs(todaysDate - lastrunDate);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
console.log("Step 3 :Its been " + diffDays + " day(s) Since the last run");
return data;
} else {
console.log(err);
return "";
}
});
}
async function storeTodaysDateinLastRunFile() {
console.log("Step 4 : Finally Saving the todays date in last run file: ");
await fs.writeFile("lastrundetail.txt", todaysDate, function(err) {
if (err) return console.log(err);
console.log('Step 5 : Saved the record in file');
});
return todaysDate;
}
const main = async () => {
let lastrunDate = await checkPreviousRunDate();
let storedDate = await storeTodaysDateinLastRunFile();
}
main();
Output :
Step 1 : Today's Date: 4
Step 4 : Finally Saving the todays date in last run file:
Step 5 : Saved the record in file
Step 2 :Last run was done on(MM/DD/YYYY): Fri Dec 04 2020 13:10:01 GMT+0530 (India Standard Time)
Step 3 :Its been 1 day(s) Since the last run
Expected Output :
Step 1 : Today's Date: 4
Step 2 :Last run was done on(MM/DD/YYYY): Fri Dec 04 2020 13:06:26 GMT+0530 (India Standard Time)
Step 3 :Its been 1 day(s) Since the last run
Step 4 : Finally Saving the todays date in last run file:
Step 5 : Saved the record in file