Verify if word exist in file.txt

Kamus :

i have this script, who i run in a program called 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 :

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. 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 !

How can i add a condition to this script (If b dont exist in file, stop the script and return a message)

thank you very mutch guys ! have a good day

Vadim Tor :

You can use use replace method without converting file into 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.

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.

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=405326&siteId=1