简体   繁体   中英

How to re-pull from file if data changes in NodeJS?

My javascript is currently pulling JSON data from a server I made in NodeJS. The data is coming from a google spreadsheet, so whenever I make changes to the spreadsheet the JSON data changes too.

I do not want to have to refresh my site to apply the updated spreadsheet data. How can I pull from the JSON file every time there is a change made? Someone mentioned using timestamps on the file and if the time stamp changes, then pull from the file. But I could not find an example.

Right now I am pulling data from the /latest route in my node server to my javascript. Code below:

app.get('/latest', function(req,res) {
    var fs = require('fs');
    var obj;
    fs.readFile('public/announcementCurrent.json', function (err, data) {
      if (err) throw err;
      obj = JSON.parse(data);
      res.json(obj)
    });
})

This is how I call the route in my javascript: $http.get(' http://localhost:3000/latest ')

How can I call the route again when the announcementCurrent.json file changes without having to refresh?

Any help would be great thanks!

The way to get updated data in real time in javascript without having to refresh the page is the whole idea of XMl Http requests, aka AJAX.

Basically you will need, at some time interval or user action of your choice, query the Google API to get the latest data and update your page accordingly.

You should try to get more informations about how to make an ajax call, and how to query the google spreadsheet API. Basically, using jQuery for instance (hum), it would look like:

$.get('http://google-spreadsheet-api-url', function( data ) {
  // Dynamically refresh the content of the page using data
})

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