Skip to content

Instantly share code, notes, and snippets.

@skw
Forked from finalclass/rework-middleware.js
Created July 3, 2013 19:53
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 skw/5922170 to your computer and use it in GitHub Desktop.
Save skw/5922170 to your computer and use it in GitHub Desktop.
/*jshint node:true*/
'use strict';
var path = require('path'),
url = require('url'),
when = require('when'),
ffs = require('final-fs');
var reworkRecompile = function (cssPath, reworkPath, doRework) {
return ffs.readFile(reworkPath, {encoding: 'utf-8'})
.then(function (reworkText) {
return ffs.writeFile(cssPath, doRework(reworkText), {encoding: 'utf-8'});
});
};
/**
* Returns connect middleware.
*
* This middleware reads the url path and if the path has .css suffix
* it tries to find .rewrite.css file, compare it mtime and if there ware changes
* it compiles the .rewrite.css file using options.doRework function.
* Next it saves this file into the requested path.
*
* @license Public Domain - do what ever you want with this code.
* @example
*
* var reworkMiddleware = require('rework-middleware');
*
* function doRework(css) {
* return rework(css)
* .use(rework.prefixValue('linear-gradient'))
* .use(rework.prefixValue('radial-gradient'))
* .use(rework.prefixValue('transform'))
* .use(rework.vars())
* .use(rework.colors())
* .toString();
* }
*
* app.use(reworkMiddleware({cssPath: __dirname + '/public', doRework: doRework})
*
* @param {Object} options
* @param {string} options.cssPath
* @param {function(string):string} options.doRework
* @returns {Function}
*/
module.exports = function (options) {
return function (req, res, next) {
var cssPath, reworkPath;
if ('GET' !== req.method && 'HEAD' !== req.method) {
return next();
}
cssPath = url.parse(req.url).pathname;
cssPath = path.join(options.cssPath, cssPath);
if (/\.css$/.test(cssPath)) {
reworkPath = cssPath.replace('.css', '.rework.css');
when.all([ffs.exists(reworkPath), ffs.exists(cssPath)])
.then(function (exists) {
if (!exists[0]) {
throw new Error('File does not exists');
} else if (!exists[1]) {
return {force: true};
} else {
return when.all([ffs.stat(reworkPath), ffs.stat(cssPath)]);
}
})
.then(function (stats) {
if (stats.force === true || stats[0].mtime > stats[1].mtime) {
return reworkRecompile(cssPath, reworkPath, options.doRework);
}
})
.ensure(function () {
next();
});
} else {
next();
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment