Mit
Mit

Reputation: 349

SetTimeout + fs.writeFile erases my object

I have an object "rooms" and I'am trying to print it's content into a file "logging.json" every 10 seconds.

setTimeout(function(){
  fs.writeFile('./logging.json',JSON.stringify(rooms,null,'\t'),function(err) {
    if(err) return console.error(err);
    console.log('done');
  });
}, 10000);

The first time (after 10 seconds) it works and I got my file logging.json completed. But the second time that the function is called, the content of my object "rooms" is erased and the logging.json file that I obtain is also empty.

Also, the rest of my program works correctly withaout this portion of code so I don't think it's coming from something else.

Could you tell please my why I'm getting this and how to fix it?

EDIT: This is what I get in the console when I try to print the my room object.

[nodemon] restarting due to changes...
[nodemon] starting `node serveur.js`
[ { username: 'Bob', message: 'Hello' },
done
[nodemon] restarting due to changes...
[nodemon] starting `node serveur.js`
[]
done

Also, I don't get why the server restars every 10 seconds, it's not supposed to.

Upvotes: 0

Views: 513

Answers (1)

dan
dan

Reputation: 1984

As you're using nodemon, you need to tell nodemon to ignore the file you're writing otherwise you entire app will restart every your update the file. This can be done via the command line like this:

nodemon --ignore logging.json app.js

Or by updating your nodemon config.

If you want to run the function every 10 seconds, you need to use setInterval rather than setTimeout. setTimeout will only run once, in 10 seconds.

To replace all content in the file every 10 seconds:

const fs = require('fs')

let count = 0

setInterval(function() {
    fs.writeFile('./test.txt', count, function (err) {
        if(err) {
            console.log(err)
        }
    })
}, 10000)

To append the file every 10 seconds:

const fs = require('fs')

let count = 0

setInterval(function() {
    const text = count++ + '\n'
    fs.appendFile('./test.txt', text, function (err) {
        if(err) {
            console.log(err)
        }
    })
}, 10000)

Upvotes: 2

Related Questions