Skip to content

Instantly share code, notes, and snippets.

@hapticdata
Created August 10, 2012 01:14
Show Gist options
  • Save hapticdata/3309952 to your computer and use it in GitHub Desktop.
Save hapticdata/3309952 to your computer and use it in GitHub Desktop.
Watches all .less files and renders css with every change
#!/usr/bin/env node
/**
* Watches all project .less files,
* automatically renders css with every change
* usage: $watch-less ~/Sites/myProject1 ~/Sites/myProject2
*/
var less = require('less'),
fs = require('fs');
var VERBOSE = (process.argv.indexOf('-v') > -1);
if ( VERBOSE ){
process.argv.splice( process.argv.indexOf('-v'), 1 );
}
var directories = ['/../app/stylesheets'];
var argvDirectories = [].slice.call(process.argv, 2, process.argv.length);
directories = directories.concat( argvDirectories );
directories.forEach(watchDirectoryForLess);
function watchDirectoryForLess( dir ){
var absolutePath = __dirname + dir;
fs.readdir(absolutePath, function (err, files){
if(err) {
console.log('There was an error reading your directory');
if(VERBOSE)console.log( err );
} else {
forEachLessFileIn( files, function(path){
var absoluteFilepath = absolutePath + '/' + path;
console.log('Watching', absoluteFilepath);
fs.watch(absoluteFilepath, function(event, filename){
renderFile(absoluteFilepath);
});
});
}
});
}
function forEachLessFileIn (files, fn){
files
.filter(function(path){
return path.match(/\.less$/); // Filter not .less files
})
.forEach(fn);
}
function renderFile(filename){
fs.readFile(filename, function(err, lessCss){
if(err) {
console.log('There was an error reading your less file');
if(VERBOSE)console.log( err );
} else {
lessCss = lessCss.toString();
less.render(lessCss, function(err, css) {
if( err ){
console.log('There was an error rendering your CSS file');
if(VERBOSE)console.log( err );
} else {
var newFilename = filename.replace(/\.less$/, '.css');
fs.writeFile(newFilename, css);
console.log( new Date().toString() + ' saved '+newFilename );
}
});
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment