我的脚本有问题,我是Node.JS的初学者。我运行 Ubuntu Linux 。
问题详情:
我有一个脚本每秒写一次文件(mini.json)很多次。另一个脚本在文件更改时读取该文件(mini.json)。问题在于读取文件的第二个脚本。
这是读取文件的应用
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");
}
});
});
这是文件(使用readFileSync加入)
{
"data1" : "random_string1",
"data2" : "random_string2",
"parities" : [
{
"data3" : "random_string3",
"data4" : "random_string4",
"data5" : "random_string5"
}
]
}
这就是错误。我只输出了控制台的最后30行
注意:在几千次执行后发生错误。
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$