Skip to content

Instantly share code, notes, and snippets.

@aseemk
Created June 29, 2011 08:12
Show Gist options
  • Save aseemk/1053401 to your computer and use it in GitHub Desktop.
Save aseemk/1053401 to your computer and use it in GitHub Desktop.
Node require watcher: exits the process when any require()'d files are changed.
# require-watcher.coffee
# Watches files that have been require()'d, and if they change, exits the
# current process, assuming that node-supervisor will then restart it.
fs = require 'fs'
# watch handler to exit the process on file changes:
watchFile = (filename) ->
fs.watchFile filename, (oldStat, newStat) ->
# we only care about files being modified; ignore events where the
# last modified time hasn't changed.
if newStat.mtime.getTime() is oldStat.mtime.getTime()
return
# otherwise, we have a file change! crash this sucker!
console.log "File changed; exiting: #{filename}"
process.exit 0
# wrapped require handlers to watch all required files:
for ext, handler of require.extensions
require.extensions[ext] = (module, filename) ->
watchFile filename
handler module, filename
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment