Skip to content

Instantly share code, notes, and snippets.

@brianleroux
Last active January 4, 2016 00:59
Show Gist options
  • Save brianleroux/8545047 to your computer and use it in GitHub Desktop.
Save brianleroux/8545047 to your computer and use it in GitHub Desktop.
example of implementing a file watcher with an http endpoint for client.js to poll for reloads
function checkForReload() {
var xhr = new XMLHttpRequest
xhr.open('get', 'http://localhost:1978', true)
xhr.setRequestHeader('X-Requested-With','XMLHttpRequest')
xhr.onreadystatechange = function() {
if (this.readyState === 4 && /^[20]/.test(this.status)) {
var reload = JSON.parse(this.responseText).reload
if (reload) window.location.reload()
}
}
xhr.send()
}
setInterval(checkForReload, 1000*5)
var Gaze = require('gaze').Gaze
, watches = ['www/*', 'test/*']
, watch = new Gaze(watches)
, http = require('http')
, reload = false
watch.on('ready', function(watcher) {
console.log('Watching ', watches)
})
watch.on('all', function(event, filepath) {
reload = true
console.log(event, filepath, ' sending reload')
})
function reloader(req, res) {
res.writeHead(200, {'Content-Type':'text/json'})
res.end(JSON.stringify({reload:reload}))
// reset reload
console.log('Reload requested')
reload = false
}
http.createServer(reloader).listen(1978, function() {
console.log('Watch server on http://localhost:1978')
})
@pmuellr
Copy link

pmuellr commented Jan 21, 2014

why poll? just have the server not return anything until the watch trips; then the client reloads when the get returns anything; maybe you'll need to dribble out a byte or so every 30 seconds or so to keep the browser from closing the XHR?

I'd actually use something like this, but in my case, when my "code" changes, I kill the server and relaunch it; same client code waiting for the "end" of the response might just work there too, but I'm a little worried the port might go into a zombie state with the browser request being open ...

@mikeal
Copy link

mikeal commented Jan 21, 2014

Keep in mind that there is a huge watch delay on Mac OS X. I've seen it be over a minute. Nothing you can do about it, it's their awful fs and kernel :(

@suskind
Copy link

suskind commented Jan 21, 2014

Quick tip: Use setTimeout recursively instead setInterval. Browsers are stopping setIntervals in unfocused tabs/windows

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment