简体   繁体   中英

Writing to file at regular intervals in Nodejs

I have a value A that is found via an async call. A will keep changing. So I want to do something like logging this every 10 seconds, and writing the value of A to file with a timestamp.

So I took this as a starting point https://codereview.stackexchange.com/questions/141329/write-log-file-in-nodejs-with-setinterval

var fs = require('fs');
var tStamp = new Date().now;
// getA() is the a async function
async function log(){
    fs.appendFile('c:/log.txt', tStamp + getA() , (err) => {
        if (err) throw err;
        logText = '';
    }); 
}
setInterval(log, 5000);

It doesn't work though. The function does not call repeatedly. It just seems to be called once, which obviously isn't what I hoped for. I thought maybe using something like

var pieceOfLog = await getA();

internally in the above functon might help things, but it didn't. So what to do here? How to

  • get the value of A
  • log it
  • repeat ad infinitum.

Should I be using a totally different approach? Did I make a stupid mistake in my code? Should I just use some library like Cron to do this for me?

new Date().now is undefined . Change that to Date.now() . It's a static function.

Make sure getA() really is async?

Beyond that...

If you don't need precision--like, if it's OK that it happens after 10.25 seconds one time, and then 10.12 seconds next time, etc.--then setInterval(functionThatLogs, 10000) should do it. Just make sure functionThatLogs is a function that quickly appends to the file.

If the file is large or the data you are writing is significant, you may want to look into pipes, streams, etc. But your question about how to log every 10 seconds...that's the easiest solution probably.

Here's a simplified version of the code you provide that works for me. I hope it works for you too. It removes getA() so if this code works and yours doesn't, it seems likely that there's an issue with getA() .

var fs = require('fs');
var path = require('path');
async function log(){
    fs.appendFile(path.join(__dirname, 'log.txt'), Date.now() + '\n', (err) => {
        if (err) throw err;
        logText = '';
    }); 
}
setInterval(log, 5000);

What is the signature of getA() ? Does it return promise? If yes, then:

async function log(){
    var tStamp = new Date().now;
    var a = await getA();
    fs.appendFile('c:/log.txt', tStamp + a, (err) => {
        if (err) throw err;
        logText = '';
    }); 
}
setInterval(log, 5000);

should work. If it does not, do you see any error?

And you most likely should use fs.appendFileSync to avoid possible async issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM