I have a file where I'm trying to replace multiple strings with other strings in an object.
Currently I have the following:
fs.readFile('myfile.txt', 'utf8', function(err, data) {
let formatted
for (var key in obj){
let re = new RegExp('(?<=config.' + key + ' = ).*(?=)', 'g');
formatted = data.replace(re, `'${obj[key]}'`)
}
fs.writeFile('myfile.txt', formatted, 'utf8', function(err) {
if (err) return console.log(err);
})
})
This works however writeFile does overwrite the entire file each time so only one string ends up getting changed and saved at the end of the loop instead of having all of them. Is there a way where I can add all the changes in at once?
I have tried using replace and doing something like from other answers I've seen.
let regexStr = Object.keys(obj).join("|")
let re = new RegExp(`(?<=config.${regexStr}+[ ]=).*(?=)`, 'g')
let format = data.replace(re, match => obj[match]);
This doesn't seem to work unless I use regexStr and not re. However, I need that specific regex that is shown in re.
I've also tried
let result = data.replace(re, function (match, key, value){
obj[key] = value || key
})
But that just results in undefined.
Is there a way to tweak that replace to get it right? Or perhaps to read the file, loop through the whole thing, and write it all at once with the changes?