Created
March 16, 2016 10:38
-
-
Save lsongdev/5dd1b93f3506b83176a9 to your computer and use it in GitHub Desktop.
simple css parser
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
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