2017-10-13 36 views
2

初學者的問題,因爲我是網絡編程的新手。我正在使用MEAN堆棧並在服務器中編寫JSON文件,以便爲任何連接的客戶端提供一些天氣信息。Node.js更新客戶端可訪問的JSON文件

我正在使用node-schedule庫每小時更新一次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; 
}); 

回答

0

的NodeJS是單線程環境。

但是讀取和寫入文件節點啓動外部進程,最終可以訪問文件以同時進行讀取和寫入。在這種情況下,併發不由Node處理,而由Operational System處理。

如果您認爲此併發可能會損害您的程序,請考慮使用鎖定文件作爲註釋並解釋here

+0

有道理,感謝您的幫助。 – JeanLucLaForge