Skip to content

Instantly share code, notes, and snippets.

@finalclass
Last active December 17, 2015 00:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save finalclass/5521272 to your computer and use it in GitHub Desktop.
Save finalclass/5521272 to your computer and use it in GitHub Desktop.
Rework css framework middleware for connect.
/*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();
}
};
};
@skw
Copy link

skw commented Jul 3, 2013

Are you going to create this as an npm module?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment