Search code examples
node.jsexpressfswritefile

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?


Solution

  • Well, you're not executing replace() on the same dataset, and you're writing down only the first change. Javascript strings are immutable, so .replace() doesn't change the original data. Try keeping the common data container:

    // ...
    
    data = data.replace(/##backgroundColor##/g, req.body.backgroundColor);
    data = data.replace(/##textColor##/g, req.body.textColor);
    
    fs.writeFile('main.scss', data, (err) => {
    
    // etc.