【问题标题】:Find String in a Txt File, Delete Entire Line在 Txt 文件中查找字符串,删除整行
【发布时间】:2014-05-16 11:54:18
【问题描述】:

我目前正在使用 node.js 创建一个 IRC 机器人。该机器人允许用户将歌曲链接添加到数据库。每次有人提交歌曲时,它都会被添加到“shuffle.txt”的新行中,如下所示:

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

请注意,user1 在其最新添加的信息中输入错误。我正在尝试创建一个 UNDO 命令,以便用户可以删除他们最近输入的行。我计划通过在 shuffle.txt 中找到他们名字的最新出现并删除它所在的整行来做到这一点。这是我的消息监听器:

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
            }

    }
});

输入命令的用户存储为from

我假设我必须按照以下方式做一些事情:

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

}

我是 JavaScript 新手,这是我第一次使用 node.js,所以我可以使用我能获得的任何帮助!谢谢大家。

编辑:我还应该指出,我不需要命令识别方面的帮助。我只需要查找/删除部分的帮助。干杯!

【问题讨论】:

    标签: javascript node.js fs


    【解决方案1】:

    Edit2:使用新解决方案进行编辑。

    你可以试试这个:

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

    将文件分成几行,用一个简单的循环向后查找最后一行,使用delete 删除该行,然后将其修补在一起。

    demo

    此外,您不应该在节点中使用readFileSync,因为阻塞节点可能很危险,因为它是单线程的。

    【讨论】:

    • 感谢您的快速回复!我在这里看到的唯一问题是,这段代码是找到最后一次出现 user1 还是第一次出现?如果我删除第一次出现,那将是删除他们最旧的提交而不是他们最新的提交。再次感谢!!
    • 天哪,你的速度很快,非常感谢您的帮助。不幸的是,我从下午 3 点开始就一直在研究这个机器人,现在是凌晨 5 点 23 分,我得睡觉了。我明天再回来看看,让你知道它是如何工作的!干杯!
    • 我已经很接近了!您最新的编辑工作就像一个绝对的宝石。我似乎遇到的唯一问题是,当我执行fs.writeFile('shuffle.txt', data_array, function (err) {}); 时,它会重写文件而没有任何换行符。
    • 从头开始!能够使用var newData = data_array.join("\r\n"); 来解决这个问题,但是现在我在 shuffle.txt 的末尾有一个额外的换行符,我需要摆脱它。
    • 全部完成!它像梦一样工作!只需添加newData = newData.slice(0, - 1); 即可删除最后一个'\n'。非常感谢您的帮助!
    【解决方案2】:

    这似乎工作正常。它是自包含的,因此您只需粘贴到 HTML 文件中即可查看它的运行情况。 基本上继续运行正则表达式以匹配从传递的用户名开始的整行。整行作为字符串返回(正则表达式的“gm”部分告诉它一次匹配一行)。

    然后您只需替换数据中返回的行(作为字符串)。 请注意,这假定该行在文本文件中是唯一的。如果您认为人们可能多次输入同一行(但只想删除最后一行),那么我未注释的“非懒惰”选项是最好的。我还没有测试如果该行在数据中的第一个或最后一个会发生什么。

    <html>
    <head>
    <script type="text/javascript">
    var sData="user1,The Beatles,Yesterday,(youtube link)\nuser2,The Rolling Stones,Angie,(youtube link)\nuser1,The Bealtes,Yellow Sumbarine,(youtube link)\nuser3,The Rolling Stones,Angie,(youtube link)";
    
    function replaceLastEntry(sText) {
      sNewData=sData;
      var re=new RegExp("^"+sText+".*$","gm"); // matches whole lines starting with sText 
    
      var lastIndex=-1;
      var i=0;
      var sMatch=re.exec(sData)!= null;
      while (sMatch!=null)
        {
        i++
        lastIndex=re.lastIndex;
        lastMatch=sMatch.toString(); // make note of last successful match - gives full line
        sMatch=re.exec(sData);
      }
    
      // at this point lastMatch contains the whole line which needs to be removed.
      // lastIndex is the string position of the character after the LAST string matched (ie the end of the matched line)
      // sNewData = sData.replace(lastMatch,""); // Lazy way - assumes the line is unique within the file
    
      // non-lazy way : locate the text by position returned and remove it
      sNewData = sData.substr(0, lastIndex-lastMatch.length-1) +   sData.substr(lastIndex);
    
      document.getElementById("Data").innerHTML=sData
      document.getElementById("NewData").innerHTML=sNewData
      document.getElementById("LastMatch").innerHTML=lastMatch
    }
    
    </script>
    </head>
    
    
    <body onload="replaceLastEntry('user1','newvalue')">
    Data: <pre id="Data"></pre>
    New Data:<pre id="NewData"></pre>
    Last Match: <pre id="LastMatch"></pre>
    </body>
    </html>
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2013-12-23
      • 2018-10-18
      • 1970-01-01
      • 2021-03-17
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多