Skip to content

Instantly share code, notes, and snippets.

@rclark
Created December 21, 2012 17:06
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 rclark/4354108 to your computer and use it in GitHub Desktop.
Save rclark/4354108 to your computer and use it in GitHub Desktop.
Watch a directory of Jade files and write them out to JavaScript functions.
watch = require 'watch'
fs = require 'fs'
pathutil = require 'path'
jade = require 'jade'
watchDir = process.argv[2] || '.'
outFile = process.argv[3] || './templates.js'
namespace = process.argv[4] || 'Templates'
isJadeFile = (fileOrDir) ->
return fileOrDir.slice(fileOrDir.length-5) is '.jade'
compileFile = (filepath) ->
fileContents = fs.readFileSync filepath, 'utf8'
return jade.compile fileContents,
client: true
compileDebug: false
filename: filepath
pretty: true
buildFunctionName = (filename) ->
fnName = filename.replace '.jade', ''
return "#{namespace}.#{fnName}"
functionString = (fn, fnName) ->
return fn.toString().replace('function anonymous(', "function #{fnName}(")
writeOut = (outStream, fnStr) ->
outStream.write fnStr
return
parseDir = (dirname, outStream) ->
filenames = fs.readdirSync dirname
for filename in filenames
continue if filename.slice(0,1) is '.'
filepath = pathutil.join dirname, filename
stat = fs.statSync filepath
if stat.isDirectory()
parseDir filepath
else if stat.isFile() and isJadeFile(filepath)
fn = compileFile filepath
fnName = buildFunctionName filename
fnStr = functionString fn, fnName
writeOut outStream, fnStr
writeJs = ->
outStream = fs.createWriteStream outFile,
flags: 'w'
parseDir watchDir, outStream
watch.createMonitor watchDir, (monitor) ->
monitor.on 'created', (filepath, stat) ->
writeJs()
return
monitor.on 'changed', (filepath, currStat, prevStat) ->
writeJs()
return
monitor.on 'removed', (filepath, stat) ->
writeJs()
return
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment