Print timestamp in a file not changing timestamp value

こ雲淡風輕ζ 提交于 2019-12-11 18:32:00

问题


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

来源:https://stackoverflow.com/questions/55707022/print-timestamp-in-a-file-not-changing-timestamp-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!