【问题标题】:Verify if word exist in file.txt验证 file.txt 中是否存在单词
【发布时间】:2020-07-16 16:02:22
【问题描述】:

我有这个脚本,我在一个名为 discord bot maker 的程序中运行它。我试图让机器人在 txt 文件中搜索一个单词,然后删除这个单词并保存文件:

let fs = require('fs');
let a = tempVars('a');
let b = tempVars('carte');

fs.readFile(`resources/${a}.txt`, { encoding: 'utf-8' }, (err, data) => {
  if (err) throw err;

  let dataArray = data.split('\n'); // convert file data in an array
  const searchKeyword = `${b}`; // we are looking for a line, contains, key word 'user1' in the file

  const key = dataArray.filter((arr) => arr.includes(searchKeyword));
  const index = key.length >= 1 && dataArray.indexOf(key[0]);
  if (index > -1) dataArray.splice(index, 1);

  // UPDATE FILE WITH NEW DATA
  // IN CASE YOU WANT TO UPDATE THE CONTENT IN YOUR FILE
  // THIS WILL REMOVE THE LINE CONTAINS 'user1' IN YOUR shuffle.txt FILE
  const updatedData = dataArray.join('\n');
  fs.writeFile(`resources/${a}.txt`, updatedData, (writeErr) => {
    if (writeErr) throw err;
    console.log('Successfully updated the file data');
  });
});

tempVars("xx") 变量是由一个名为 discord bot maker 的程序给出的,所以没有问题。 我的问题是当txt文件中不存在var“b”(谁是discord命令的参数)时,脚本会删除文件中的第一个单词!

如何向此脚本添加条件(如果文件中不存在 b,则停止脚本并返回消息)

非常感谢你们!祝你有美好的一天

【问题讨论】:

    标签: javascript file


    【解决方案1】:

    您可以使用replace 方法,而无需将文件转换为数组。

    let fs = require('fs');
    let a = tempVars('a');
    let b = tempVars('carte');
    
    fs.readFile(`resources/${a}.txt`, { encoding: 'utf-8' }, (err, data) => {
      if (err) throw err;
    
      const updatedData = data.replace(b, '');
    
      fs.writeFile(`resources/${a}.txt`, updatedData, (writeErr) => {
        if (writeErr) throw err;
        console.log('Successfully updated the file data');
      });
    });
    

    此方法将仅替换第一个匹配的单词。如果你想替换所有匹配的单词,作为第一个参数,你可以使用正则表达式。 Char g 代表全局,m 代表多行。

    const regex = new RegExp(b, 'gm')
    
    data.replace(regex, '');
    

    如果你想测试文件是否包含请求的单词,你可以使用.includes函数和if语句。

    if (!data.includes(b)) {
      console.log("Requested word is not present in file")
      // Your logic here
      return
    }
    

    【讨论】:

    • 哦,它解决了第一个单词被删除的问题,即使该单词不在文件中。你现在知道当单词不在列表中时我如何发送消息吗?无论如何,非常感谢。
    • 好吧,const updatedData = data.replace(b, a);用a替换b,但我需要删除文件的b,a只是文件名:D
    • @Kamus 我已经更新了答案。如果您对我的回答感到满意,您可以认为它是正确的。
    • @Kamus 另外我建议使用更好的变量名。
    • 它与 .include 函数一起使用!谢谢楼主!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 2011-10-30
    • 2018-05-06
    相关资源
    最近更新 更多