I'm having an issue with my code below, where my config
variable is being updated in some area, but in the function within http.createServer
, it isn't changing. I have some comments to indicate what's going on in the code below. My guess is config is being held onto somewhere, or I don't understand JavaScript scope as well as I thought. Can anyone explain what's going on here?
EDIT: it looks like what was happening is the client & server were keeping the socket open because of the Connection: keep-alive
header. For the time being (because this is meant to be a local server with low traffic), I've added res.setHeader('Connection','close');
which appears to fix this issue when using the same client to connect in short intervals after a configuration change.
// global variables & configuration
var fs = require('fs');
var utils = require('./utils.js');
var configFile = 'config.json';
var initialConfig = JSON.parse(fs.readFileSync(configFile));
var server = {};
// watch file system for changes to configuration
fs.watchFile(configFile, function(curr, prev) {
console.log('config change detected');
// reload the configuration
var config = JSON.parse(fs.readFileSync(configFile)); // config is correct
if (typeof server !== 'undefined') {
server.close();
}
serveStatic(config);
});
// start the server
serveStatic(initialConfig);
// server functions
function serveStatic(config) {
var http = require('http'); // config is the new (correct) value
var startTime;
server = http.createServer(function(req, res) { // config is the old value, never changes
try {
// solution: res.setHeader('Connection','close');
res.end(JSON.stringify(config));
} catch (err) {
if (res.statusCode === 200)
res.statusCode = 500;
res.write(http.STATUS_CODES[res.statusCode]);
if (config.detailed_errors)
res.write('\n' + err);
res.end();
}
});
console.log('Starting server on port ' + config.port);
server.listen(config.port);
}