简体   繁体   English

如果NodeJS中的数据发生更改,如何从文件中重新拉出?

[英]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. 我的JavaScript当前正在从我在NodeJS中制成的服务器中提取JSON数据。 The data is coming from a google spreadsheet, so whenever I make changes to the spreadsheet the JSON data changes too. 数据来自Google电子表格,因此,每当我对电子表格进行更改时,JSON数据也会随之更改。

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? 每次进行更改时,如何从JSON文件中提取? 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. 现在,我正在将数据从节点服务器中的/ latest路由拉至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 ') 这就是我在javascript中调用路由的方式:$ http.get(' http:// localhost:3000 / latest ')

How can I call the route again when the announcementCurrent.json file changes without having to refresh? 当announcementCurrent.json文件更改而无需刷新时,如何再次调用该路由?

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. 无需刷新页面即可在javascript中实时获取更新数据的方法是XMl Http请求(也称为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. 基本上,您需要在一定时间间隔或您选择的用户操作下,查询Google API以获取最新数据并相应地更新页面。

You should try to get more informations about how to make an ajax call, and how to query the google spreadsheet API. 您应该尝试获取有关如何进行Ajax调用以及如何查询Google电子表格API的更多信息。 Basically, using jQuery for instance (hum), it would look like: 基本上,使用jQuery作为实例(嗡嗡声),它看起来像:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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