Skip to content

Instantly share code, notes, and snippets.

@lsongdev
Created March 16, 2016 10:38
Show Gist options
  • Save lsongdev/5dd1b93f3506b83176a9 to your computer and use it in GitHub Desktop.
Save lsongdev/5dd1b93f3506b83176a9 to your computer and use it in GitHub Desktop.
simple css parser
const fs = require('fs');
function notEmpty(input){
return !!input.trim();
};
function kv(prop){
var obj = {};
prop.split(/;/g).filter(notEmpty).forEach(function(item){
var p = item.split(':');
obj[ String(p[0]).trim() ] = String(p[1]).trim()
})
return obj;
}
const content = fs.readFileSync('a.css', 'utf8')
const rules = content.replace(/\s/g, '').replace(/\}/g, '}\n').split(/\n/g).filter(notEmpty).map(function(rule){
var tokens = rule.match(/^(.+)\{(.+)\}$/);
return {
selector: tokens[1],
content : tokens[2],
props : kv(tokens[2])
};
});
console.log(rules);
/*
➜ css-parser node .
[ { selector: '.selector',
content: 'color:#fff;font-size:14px;',
props: { color: '#fff', 'font-size': '14px' } },
{ selector: 'html',
content: 'background:red;',
props: { background: 'red' } },
{ selector: 'a',
content: 'text-align:center;',
props: { 'text-align': 'center' } } ]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment