Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/389.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在Txt文件中查找字符串,删除整行_Javascript_Node.js_Fs - Fatal编程技术网

Javascript 在Txt文件中查找字符串,删除整行

Javascript 在Txt文件中查找字符串,删除整行,javascript,node.js,fs,Javascript,Node.js,Fs,我目前正在使用node.js创建一个IRC机器人。bot允许用户向数据库添加歌曲链接。每次有人提交歌曲时,它都会添加到“shuffle.txt”的新行中,如下所示: 请注意,user1在其最新添加的内容中错误地键入了一些信息。我正在尝试执行撤消命令,以便用户可以删除最近输入的行。我计划通过在shuffle.txt中查找他们名字的最新版本并删除在其中找到的整行内容来实现这一点。以下是我的消息侦听器: bot.addListener('message', function(from, to, mes

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

请注意,user1在其最新添加的内容中错误地键入了一些信息。我正在尝试执行撤消命令,以便用户可以删除最近输入的行。我计划通过在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
            }

    }
});
输入命令的用户存储为来自

我假设我必须做一些类似的事情:

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,所以我可以使用任何我能得到的帮助!谢谢大家


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

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
删除该行,然后将其重新拼接在一起


另外,您不应该在节点中使用
readFileSync
,因为阻塞节点可能是危险的,因为它是单线程的。它是自包含的,所以您可以将其粘贴到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>

var sData=“user1,披头士乐队,昨天,(youtube链接)\nuser2,滚石乐队,安吉,(youtube链接)\nuser1,贝尔特乐队,黄色桑巴林,(youtube链接)\nuser3,滚石乐队,安吉,(youtube链接)”;
函数replaceLastEntry(sText){
sNewData=sData;
var re=new RegExp(“^”+sText+“*$”,“gm”);//匹配以sText开头的整行
var lastIndex=-1;
var i=0;
var sMatch=re.exec(sData)!=null;
while(sMatch!=null)
{
我++
lastIndex=re.lastIndex;
lastMatch=sMatch.toString();//记下上次成功的匹配-给出完整的一行
sMatch=重新执行(sData);
}
//此时,lastMatch包含需要删除的整行。
//lastIndex是最后一个匹配字符串后的字符的字符串位置(即匹配行的末尾)
//sNewData=sData.replace(lastMatch,“”;//Lazy-way-假定该行在文件中是唯一的
//非惰性方式:按返回的位置定位文本并将其删除
sNewData=sData.substr(0,lastIndex lastMatch.length-1)+sData.substr(lastIndex);
document.getElementById(“数据”).innerHTML=sData
document.getElementById(“NewData”).innerHTML=sNewData
document.getElementById(“LastMatch”).innerHTML=LastMatch
}
数据:
新数据:
最后一场比赛:

希望这有帮助

谢谢你的快速回复!我在这里看到的唯一问题是,这段代码是查找最后一次出现的
user1
还是第一次出现的?如果我删除了第一次提交,那将是删除他们最早的提交,而不是最新的提交。再次感谢!!天啊,你很快,非常感谢你的帮助。不幸的是,我从下午3点就开始做这个机器人了,现在已经是早上5:23了,我得睡一会儿了。我明天会回来让你知道它是如何工作的!干杯我好近啊!你最新的编辑工作就像一块宝石。我似乎遇到的唯一问题是,当我执行
fs.writeFile('shuffle.txt',data_数组,function(err){})时它在没有任何换行符的情况下重写文件。划掉它!能够使用
var newData=data\u array.join(“\r\n”)newData=newData.slice(0,-1)
删除最后一个“\n”。非常感谢你的帮助!
<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>