【问题标题】:Node.js update client-accessible JSON fileNode.js 更新客户端可访问的 JSON 文件
【发布时间】:2017-10-13 13:31:29
【问题描述】:

一个初学者的问题,因为我是网络编程新手。我正在使用 MEAN 堆栈并在服务器中编写一个 JSON 文件,以便为任何连接的客户端提供一些天气信息。

我使用节点调度库每小时更新一次 JSON 文件。如果客户端碰巧同时尝试访问文件的数据,从服务器不断更新文件会导致任何并发问题吗?

代码如下:

server.js

function updateWeatherFile() {
  var weather = require('weather-js');
  var w = "";
  weather.find({search: weatherSearch, degreeType: 'C'}, function(err, result) {
    if(err)
      console.log(err);
    w = JSON.stringify(result, null, 2);
    fs.writeFile('public/weather.json', w, function(err) {
      if(err) {
        console.log(err);
      }
    });
  });
}

if(scheduleWeather) {
  var schedule = require('node-schedule');
  var sequence = '1 * * * *';  // cron string to specify first minute of every hour
  var j = schedule.scheduleJob(sequence, function(){
    updateWeatherFile();
    console.log('weather is updated to public/weather.json at ' + new Date());
  });
}
else {
  updateWeatherFile();
}

client_sample.js

// get the current weather from the server
$http.get('weather.json').then(function(response) {
    console.log(response['data'][0]['current']);
    vm.weather = response['data'][0]["current"].skytext;
    vm.temperature = response['data'][0]["current"].temperature;
});

【问题讨论】:

    标签: javascript json node.js mean-stack


    【解决方案1】:

    NodeJs 是单线程环境。

    然而 读取和写入文件 Node 启动外部进程,最终文件可以被同时读取和写入。在这种情况下,并发不是由节点处理,而是由操作系统处理。

    如果您认为这种并发可能会损害您的程序,请考虑使用here 注释和解释的锁定文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-06
      • 2018-02-23
      • 2015-04-26
      • 1970-01-01
      • 2015-08-09
      • 2015-06-23
      • 1970-01-01
      相关资源
      最近更新 更多