I am trying to print the current timestamp in a file using Timers in Nodejs.
If I'm using setInterval
, I am able to print the current timestamp in the output file, but the the value of it never changes... (it takes the first value of timestamp and then it just prints it every 1000ms....)
This was the code:
export class App {
private getData() {
return Date.now();
}
private async printToFile(path: string, data: number) {
try {
fs.writeFile(path, data + '\n', { 'flag': 'a' }, function (err) {
if (err) {
console.error(err);
}
});
//setTimeout(this.printToFile, 1000, path, this.getData());
}
catch (err) {
throw err;
}
}
async run() {
try {
//setTimeout(this.printToFile, 1000, "output.txt", this.getData());
let interval = setInterval(this.printToFile, 1000, "output.txt", this.getData());
}
catch (err) {
console.error(err)
}
}
}
I've also tried to use setTimeout
(commented the line with setInterval
from the run() method and used the 2 lines that are right now commented); the result of this was:
UnhandledPromiseRejectionWarning: TypeError: this.getData is not a function
OK. If I put Date.now()
instead of this.getData()
, it gives me a new error:
UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_CALLBACK]: Callback must be a function
(regarding this.printToFile
.... it doesn't know what printToFile
is....)
Tested it more... and if I replace all the Timers with console.log(..)
, it's working perfectly. If I add a Timer, like setTimeout(this.printToFile, 1000, "output.txt", this.getData());
in the run()
function... I get the errors that I was having before:
UnhandledPromiseRejectionWarning: TypeError: this.getData is not a function