Find String in a Txt File, Delete Entire Line

Tyler Roper picture Tyler Roper · Apr 4, 2014 · Viewed 8.4k times · Source

I'm currently working with node.js to create an IRC bot. The bot allows users to add song links to a database. Each time someone submits a song, it is added to a new line of "shuffle.txt" as such:

user1,The Beatles,Yesterday,(youtube link)
user2,The Rolling Stones,Angie,(youtube link)
user1,The Bealtes,Yellow Sumbarine,(youtube link)

Notice that user1 mistyped some information in their latest addition. I'm trying to make an UNDO command so that a user can delete their most recently entered line. I plan on doing this by finding the latest occurrence of their name in shuffle.txt and deleting the entire line that it's found on. Here's my message listener:

bot.addListener('message', function(from, to, message) {
    if (message.indexOf(config.prefix) == 0) {

        message = message.slice(1);
        var token = message.split(" ");

        if (token[0] == 'undo') {
              //find and delete
            }

    }
});

the user entering the command is stored as from

I'm assuming I'll have to do something along the lines of this:

var songList = fs.readFileSync('shuffle.txt', 'utf8');
var position = songList.indexOf(from);

if (position != -1) { //if 'from' found

  //find LAST occurrence of 'from'
  //get length from here to next occurrence of '\n'
  //substr(length + 1)

  fs.writeFile('shuffle.txt', songList, function(err) {
    if (err) {
      console.log (err);
    }

}

I'm new to JavaScript and this is my first time using node.js so I can use any help I can get! Thanks everyone.

EDIT: I should also point out that I don't need help with the command recognition. I only need help with the finding/deleting portion. Cheers!

Answer

Mosho picture Mosho · Apr 4, 2014

Edit2: edited with a new solution.

You could try this:

fs.readFile('shuffle.txt', function read(err, data) {
    if (err) {
        throw err;
    }

    lastIndex = function(){
        for (var i = data_array.length - 1; i > -1; i--)
        if (data_array[i].match('user1'))
            return i;
    }()

    delete data_array[lastIndex];

});

Split file into lines, find the last line with a simple loop going backwards, remove the line using delete, then patch it back together.

demo

Also, you should not use readFileSync in node, as blocking node can be dangerous since it's single threaded.