Skip to content

Instantly share code, notes, and snippets.

@vjpr vjpr/index.coffee
Created Jun 22, 2013

Embed
What would you like to do?
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
You can’t perform that action at this time.