Kathy Wegrzynowski
Kathy Wegrzynowski

Reputation: 3

Replace different strings in file from an object in nodejs

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?

Upvotes: 0

Views: 440

Answers (1)

Bharath
Bharath

Reputation: 400

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

Upvotes: 1

Related Questions