Last active
January 4, 2016 00:59
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') | |
}) |
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
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 :(