node package manager
Orgs are free. Discover, share, and reuse code in your team. Create a free org »

watch-node

watch-node

Watch files using the fsevents built into the Mac OS

Install

npm install watch-node

Usage

watch = require 'watch-node'
 
watch './src'(file) ->
  console.log "File changed: #{file}"

Example: Automatically Restart Node Server

Here's a cake task to automatically restart the node server when it changes. Customize it however.

(JavaScript version of the example)

{spawnexec} = require 'child_process'
 
fs            = require 'fs'
path          = require 'path'
Shift         = require 'shift'
watch         = require 'watch-node'
serverPath    = "example/server.js"
 
task 'auto-reload'->
  watch path.dirname(serverPath)(file) ->
    if file.match(serverPath)
      exec 'ps aux | grep node'(e, stdout, o) ->
        lines = stdout.toString().split("\n")
        for line in lines
          if line.match(serverPath)
            match = line.match(/[^ ]+ +(\d+)/)
            if match
              pid = match[1]
              exec "kill -2 #{pid}"
              exec "node #{serverPath}"
              console.log "Server restarted... node #{serverPath}"

Example: Automatically Compile CoffeeScript, Stylus, Less, etc.

Here's a cake task to watch JS/CSS templates and recompile them. It works with any file.

fs      = require 'fs'
path    = require 'path'
watch   = require 'watch-node'
Shift   = require 'shift'
 
task 'watch''Compile asset templates'->
  watch './src'(file, curr, prev) ->
    fs.readFile file'utf-8'(error, input) ->
      throw error if error
    
      inputExtension  = path.extname(file)
      outputExtension = switch inputExtension
        when ".coffee"".ejs" then ".js"
        when ".styl"".less"".sass" then ".css"
      engine          = Shift.engine extension
      outputPath      = file.replace(/^\.\/src/"./lib").replace(new RegExp("#{inputExtension}$")outputExtension)
    
      engine.render input(error, output) ->
        fs.writeFile outputPathoutput