0

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?

1
  • "... however writeFile does overwrite the entire file each time" - it's not writeFile, it's the way you assign the variable "formatted" to a new key each iteration of the for loop. Commented Aug 3, 2021 at 15:15

1 Answer 1

1

Try this, this will replace all the content from file and then write the update content back.

fs.readFile('myfile.txt', 'utf8', (readErr, data) => {
    if(readErr) {
        return console.log(readErr);
    } else {
        for (var key in obj){
            let re = new RegExp(`(?<=config.${key} = ).*(?=)`, 'g');
            data = data.replace(re, `'${obj[key]}'`); 
        }
        fs.writeFile('myfile.txt', data, 'utf8', (writeErr) => {
            if(writeErr) {
                return console.log(writeErr);
            } else {
                console.log('File was writen');
            }
        });
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.