Saturday 20 May 2017

nodeJS replace multiple values in one file

I want to replace N values in an existing file with placeholders.

When a post request in a ExpressJS App is fired, the placeholder values in a file have to be changed.

For example the SASS file:

$textColor: ##textColor##;
$backgroundColor: ##backgroundColor##;

And my functionality which works fine with 1 replacement:

router.post('/', function(req, res) {

    fs.readFile('main.scss', 'utf8', (err, data) => {
        if(err) {
            console.log('An error occured', err);
        }

        backgroundColorToReplace = data.replace(/##backgroundColor##/g, 
        req.body.backgroundColor);
        // This value has to be replaced as well
        textColorToReplace = data.replace(/##textColor##/g, req.body.textColor);

        fs.writeFile('main.scss', backgroundColorToReplace, (err) => {
            if(err) {
                 console.log('An error occured', err);
            }

            console.log('Colors successfully changed');
        });
    });

    res.json({
        textColor: req.body.textColor,
        backgroundColor: req.body.backgroundColor
    });
});

How can i solve this problem? Is there a way?



via derpiet

No comments:

Post a Comment