Created
June 22, 2013 08:54
-
-
Save vjpr/5840043 to your computer and use it in GitHub Desktop.
Cache compiled js of required IcedCoffeeScript files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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