Engine
Engine

Reputation: 5420

Replacing line in a file using nodejs

I need to find a line in a file and replace it with a new one, all using NodeJS. Here's what I've done to achieve that:

var fs = require('fs');

fs.readFile('infra_setting.conf', 'utf-8', function(err, data){
    if (err) throw err;
    console.log(data)
 });



 var fs = require('fs')
fs.readFile('myfile.conf', 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }
  var result = data.replace(/example/g, 'example: 12345678');

  fs.writeFile('myfile.conf', result, 'utf8', function (err) {
     if (err) return console.log(err);
  });
});

The problem I have is that the string of the line keeps changing.

1st time =>  example : 2222
2nd time =>  example : somthing else

Is there a way to localize the line and replace it by NodeJS ?

Upvotes: 0

Views: 359

Answers (2)

Mohammed Al-Reai
Mohammed Al-Reai

Reputation: 2786

try and tell me if it works or not

var fs = require('fs')

function searchReplaceFile(regexpFind, replace, FileName) {
    var file = fs.createReadStream(FileName, 'utf8');
    var newDATA= '';

    file.on('data', function (chunk) {
        newDATA+= chunk.toString().replace(regexpFind, replace);
    });

    file.on('end', function () {
        fs.writeFile(FileName, newDATA, function(err) {
            if (err) {
                return console.log(err);
            } else {
                console.log('Updated!');
            }
    });
});

searchReplaceFile(/example/g, 'example: 12345678', 'infra_setting.conf');

  

Upvotes: 1

Medet Tleukabiluly
Medet Tleukabiluly

Reputation: 11930

Here's the example where i changed line from .gitignore file

// simulate fs.readFileSync('./gitignore', { encoding: 'utf8' })
const fileContent = 'node_modules\r\npackage-lock.json\r\nyarn.lock\r\n*.code-workspace\r\n'

function changeLine(content, lineString, newLineString) {
  const delimeter = '\r\n'
  const parts = content.split(delimeter).filter(v => v.length)
  const lineIndex = parts.findIndex(v => v.includes(lineString))
  parts[lineIndex] = newLineString
  return parts.join(delimeter)
}

console.log(fileContent)
const change1 = changeLine(fileContent, 'node_modules', 'not_node_modules')
console.log(change1)
const change2 = changeLine(change1, 'package-lock.json', '.vscode')
console.log(change2)

Upvotes: 1

Related Questions