vendredi 28 août 2015

execute rule if only the target is defined in node js

I am replacing color, font and font size in the server according to the users choice in the client side. In my program user can proceed without choosing all 3 of them (the user can choose only color and font etc.), so those variable values will be undefined. My code below is only to changes all 3 variables and if its undefined, it replaces it as undefined.

    var userId = req.userId;
    var appId = req.body.appId;
    var main = 'temp/' + userId + '/templates/' + appId + '/css/main.css';

    var color = req.body.color;
    var font = req.body.font;
    var fontSize = req.body.fontSize;

    function updateFile(filename, replacements) {
        return new Promise(function (resolve) {
            fs.readFile(filename, 'utf-8', function (err, data) {
                var regex, replaceStr;
                if (err) {
                    throw (err);
                } else {
                    for (var i = 0; i < replacements.length; i++) {
                        regex = new RegExp("(\\" + replacements[i].rule + "\\s*{[^}]*" + replacements[i].target + "\\s*:\\s*)([^\\n;}]+)([\\s*;}])");
                        replaceStr = "$1" + replacements[i].replacer + "$3";
                        data = data.replace(regex, replaceStr);
             if(replacements[i].target == undefined){
                    replacements[i].rule = !replacements[i].rule;
                }//if condition which I have tried
                  }

                  fs.writeFile(filename, data, 'utf-8', function (err) {
                        if (err) {
                            throw (err);
                        } else {
                            resolve();
                        }
                    });
                }
            });
        });
    }

    updateFile(main, [

        {rule: ".made-easy-themeColor", target: "color", replacer: color},
        {rule: ".made-easy-themeFont", target: "font-family", replacer: font},
        {rule: ".made-easy-themeFontSize", target: "font-size", replacer: fontSize + "em"}
    ], function (err) {
        console.log((err));
    });

My aim is only to execut rule if target according to that is defined. I have tried putting,

 if(replacements[i].target == undefined){
    replacements[i].rule = !replacements[i].rule;
   } 

as I have mentioned above in the code but it is not working. Please can anyone tell me how to put the conditions in the above code

Aucun commentaire:

Enregistrer un commentaire