change a file using node.js

Connor Leech picture Connor Leech · Jan 21, 2014 · Viewed 39.8k times · Source

I have a text file that looks like this:

./4F6cFLnAAFc.png
./4Flj9plmKGQ.png
./4fQeHtSdw80.png
./4I9iibPLdBw.png
./4J-dRA3MGc8.png
./4mdEsouIXGM.png
./4-_-wQc3EGE.png
./595Tiga1gIg.png
./60u_ctp6UIw.png
./64bH_27Ehoc.png
./64_ZfIemRGM.png
./66pQLO--Ghk.png
./69rDtSpshAw.png
./69-YUSazuic.png

I'd like to replace the . at the beginning of each line with 'myString' using node.js. So each will end up looking like: myString/4F6cFLnAAFc.png

I am trying to use a regular expression but I suspect it can be done using read and write streams.

var fs = require('fs');

fs.readFile('filelist.txt', 'utf-8', function(err, data){
    if (err) throw err;

    console.log(typeof(data)); // string

    data.replace(/\.\/+/, 'myString');

});

What regex will work or what's the best way to edit this file using node?

Answer

psyrendust picture psyrendust · Jan 21, 2014

Here are two options for Sync or Async depending on what you want.

var fs = require('fs');

function readWriteAsync() {
  fs.readFile('filelist.txt', 'utf-8', function(err, data){
    if (err) throw err;

    var newValue = data.replace(/^\./gim, 'myString');

    fs.writeFile('filelistAsync.txt', newValue, 'utf-8', function (err) {
      if (err) throw err;
      console.log('filelistAsync complete');
    });
  });
}

function readWriteSync() {
  var data = fs.readFileSync('filelist.txt', 'utf-8');

  var newValue = data.replace(/^\./gim, 'myString');

  fs.writeFileSync('filelistSync.txt', newValue, 'utf-8');

  console.log('readFileSync complete');
}

readWriteAsync();
readWriteSync();