OutForCode
OutForCode

Reputation: 451

Reading a value of css styles using nodejs

i wan to create new css with lowest and highest value.

     table[my-type="myStyle"] {
        width: 255.388px !important;
    }

and the above code present in n number of css files in my style directory.

Upvotes: 1

Views: 357

Answers (1)

Mohamed Ramrami
Mohamed Ramrami

Reputation: 12691

You can use postcss to parse the css and get the values you want.

Here is an example of how to get min and max width from different css files (for the same selector table[my-type="myStyle"]):

const fs = require('fs');
const postcss = require('postcss');

const allWidthValues = [];

const files = [
    'styles/style-1.css',
    'styles/style-2.css',
    'styles/style-3.css'
];

const selector = 'table[my-type="myStyle"]';

const processor = postcss.plugin('processor', () => (css) => {    
    // Callback for each rule node.
    css.walkRules((rule) => {        
        // Match the individual rule selector 
        if (rule.selector.indexOf(selector) !== -1) {
            // Callback for each declaration.
            rule.walkDecls(decl => {
                // Find the width declaration
                if(decl.prop.indexOf('width') !== -1) {
                    const width = decl.value.replace('px', '') * 1;
                    allWidthValues.push(width);
                }
            })
        }
    });
});

files.forEach(file => {
    const css = fs.readFileSync(file, 'utf-8');
    postcss([processor])
        .process(css, {from : file})
        .then(() => console.log('Done processing file : ', file))
        .catch(() => console.log('Error processing file : ', file));    

});

console.log('All width values : ', allWidthValues);

allWidthValues.sort();

console.log('Min width : ', allWidthValues[0]);
console.log('Max width : ', allWidthValues[allWidthValues.length - 1]);

Upvotes: 2

Related Questions