2

A beginner's question as I am new to web programming. I am using the MEAN stack and writing a JSON file within the server in order to make some weather information available to any connected clients.

I am updating the JSON file every hour using the node-schedule library. Will the constant updating of the file from the server cause any concurrency issues if the clients happen to be attempting to access the file's data at the same time?

Code snippet below:

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;
});

1 Answers1

0

NodeJs is single threaded environment.

However To read and write files Node starts external processes and eventually the file can be accessed to read and write simultaneously. In this case the concurrency is not handled by Node, but by the Operational System.

If you think this concurrency may harm you program, consider using a lock file as commented and explained here.

dpetrini
  • 1,169
  • 1
  • 12
  • 25