Skip to content

Instantly share code, notes, and snippets.

@shreeve
Created February 9, 2018 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shreeve/31b30afa98a0183bd195523a5fdee925 to your computer and use it in GitHub Desktop.
Save shreeve/31b30afa98a0183bd195523a5fdee925 to your computer and use it in GitHub Desktop.
Simple macos-only file watcher (basic concept, not done)
#!/usr/bin/env coffee
fs = require 'fs'
fp = require 'path'
EventEmitter = require 'events'
class Watcher extends EventEmitter
constructor: (globs, cb) ->
super()
@watch globs, cb if globs?.length
watch: (globs, cb) ->
path = globs[0] # TODO: process all, not just first one
@watchPath path, cb
baseFilter: (base, cb) -> (type, path) ->
if path.startsWith(base) and (path[base.length] or '/') is '/'
type = fs.existsSync(path) and 'update' or 'remove'
cb type, path
watchPath: (path, cb) ->
parent = fp.dirname path
base = fp.basename path
@fswatcher = fs.watch parent, recursive: true
.on 'change', @baseFilter base, cb # TODO: debounce cb
@
new Watcher ['app', 'vendor'], (type, path) -> console.log "[#{type}] #{path}"
### NOTE: Test as follows:
watch.coffee &
mkdir -p app/b/c/d/e
rm -rf app
###
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment