简体   繁体   English

验证 file.txt 中是否存在单词

[英]Verify if word exist in file.txt

i have this script, who i run in a program called discord bot maker.我有这个脚本,我在一个名为 discord bot maker 的程序中运行。 I'm trying to give the bot the possibility to search for a word in a txt file, then remove this word and save the file:我试图让机器人在 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');
  });
});

the tempVars("xx") variables are given by a program named discord bot maker, so no trouble with that. tempVars("xx") 变量由名为 discord bot maker 的程序给出,所以没有问题。 My problem is that when the var "b" (who is the parameter of a command in discord) doesnt exist in the txt file, the script delete the first word in the file !我的问题是当txt文件中不存在var“b”(谁是discord命令的参数)时,脚本会删除文件中的第一个单词!

How can i add a condition to this script (If b dont exist in file, stop the script and return a message)如何向此脚本添加条件(如果文件中不存在 b,请停止脚本并返回消息)

thank you very mutch guys !非常感谢你们! have a good day祝你有美好的一天

You can use use replace method without converting file into arrays.您可以使用replace方法而不将文件转换为 arrays。

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

This method will replace only first matched word.此方法将仅替换第一个匹配的单词。 In case, if you want to replace all matched word, as a first parameter, you can use Regular Expression.如果要替换所有匹配的单词,作为第一个参数,可以使用正则表达式。 Char g is stands for global, m is for multi-line.字符g代表全局, m代表多行。

const regex = new RegExp(b, 'gm')

data.replace(regex, '');

In case you want to test if the file contains requested word, you can use .includes function and if statement.如果要测试文件是否包含请求的单词,可以使用.includes function 和if语句。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM