Skip to content

Instantly share code, notes, and snippets.

@vjpr
Created June 22, 2013 08: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 vjpr/5840043 to your computer and use it in GitHub Desktop.
Save vjpr/5840043 to your computer and use it in GitHub Desktop.
Cache compiled js of required IcedCoffeeScript files
temp = require 'temp'
fs = require 'fs'
path = require 'path'
_ = require 'underscore'
cachePath = {}
cache = {}
requireExt = (_cachePath) ->
cachePath = _cachePath or path.join process.cwd(), 'tmp/coffee.cache.json'
cache = try
JSON.parse fs.readFileSync cachePath, 'utf-8'
catch e then {}
# Taken from Iced Coffee Script
{compile, helpers} = require 'iced-coffee-script'
loadFile = (module, filename) ->
raw = fs.readFileSync(filename, "utf8")
stripped = (if raw.charCodeAt(0) is 0xFEFF then raw.substring(1) else raw)
js = compile stripped,
filename: filename
literate: helpers.isLiterate(filename)
js
# ---
require.extensions['.coffee'] = (module, filename) ->
# Read source file stats.
stats = fs.statSync filename, 'utf8'
getCached = ->
return null unless cache[filename]?
if cache[filename].mtime < stats.mtime.getTime()
return null
else
# Return cached.
fs.readFileSync cache[filename].filename, 'utf8'
if (cached = getCached())?
js = cached
else
# Compile.
js = loadFile.call @, module, filename
# Save compiled js to tmp dir.
tmpFile = temp.path suffix: '.js'
fs.writeFileSync tmpFile, js, 'utf8'
# Update cache json file.
cache[filename] or= {}
_.extend cache[filename],
filename: tmpFile
mtime: stats.mtime.getTime()
return module._compile js, filename
requireExt.save = ->
try
fs.writeFileSync cachePath, JSON.stringify(cache or {}), 'utf8'
catch e then console.error e
#requireExt.clear = ->
# if fs.existsSync(cachePath) then fs.unlinkSync(cachePath);
# initialized = false
# cachePath = undefined
module.exports = requireExt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment