nodeJS 替换一个文件中的多个值

nodeJS replace multiple values in one file

我想用占位符替换现有文件中的 N 个值。

当 ExpressJS 应用程序中的 post 请求被触发时,必须更改文件中的占位符值。

例如 SASS 文件:

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

我的功能在 1 个替换后工作正常:

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
    });
});

我该如何解决这个问题?有办法吗?

好吧,您没有在同一个数据集上执行 replace(),并且您只写下了第一个更改。 Javascript 字符串是不可变的,因此 .replace() 不会更改原始数据。尝试保留公共数据容器:

// ...

data = data.replace(/##backgroundColor##/g, req.body.backgroundColor);
data = data.replace(/##textColor##/g, req.body.textColor);

fs.writeFile('main.scss', data, (err) => {

// etc.