Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have a problem with my script and I'm beginner in Node.JS. I run Ubuntu Linux.

Problem details:

I have a script that writes a file (mini.json) many times per second. And another script that reads that file(mini.json) when the file changes. The problem is with the second script that reads the file.

This is the app that reads the file

var fs = require('fs');

app.locals.config.RandomData.forEach(function(item) {

fs.exists(item.random, function (exists) {
    if (exists) {

        var current_random_adress = item.random + '/mini.json';
        // console.log(current_random_adress);

        fs.watchFile(current_random_adress,{ persistent: true, interval: 1 }, function(curr,prev) {  // in ms
            // console.log("current mtime: " +curr.mtime);
            // console.log("previous mtime: "+prev.mtime);
            if (+curr.mtime === +prev.mtime) {

                // Do nothing because the file didn't change

            } else {
                console.log("The file have changes");

                var brute_data = fs.readFileSync(current_data, 'utf8');

                var object_parsed_from_file = JSON.parse(brute_data);


             //   console.log(object_parsed_from_file.random_string1);
                var datetime = new Date().toISOString().slice(0, 19).replace('T', ' ');

            }
        });
        console.log("Route or file exists");
    } else {
        console.log("Route or file doesn't exist");
    }
});

});

This is the file (readed with readFileSync)

  {
"data1" : "random_string1",
"data2" : "random_string2",
"parities" : [
                {
                    "data3" : "random_string3",
                    "data4" : "random_string4",
                    "data5" : "random_string5"
                }
            ]
 }

And this is the error.I outputed just the last 30 lines of the console

Note: The error occures after few thousand executions.

The file have changes
random_string1 output
The file have changes
random_string1 output
The file have changes
random_string1 output
The file have changes
random_string1 output
The file have changes

undefined:0

^
SyntaxError: Unexpected end of input
at Object.parse (native)
at StatWatcher.<anonymous> (/media/idz/01D02FC315F350A0/Dev-    Node/microapp3/app.js:318:56)
at StatWatcher.emit (events.js:98:17)
at StatWatcher._handle.onchange (fs.js:1115:10)
idz@idz-ThinkPad-Edge-E531:/media/idz/01D02FC315F350A0/Dev-Node/microapp3$ 
share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.