簡體   English   中英

驗證 file.txt 中是否存在單詞

[英]Verify if word exist in file.txt

我有這個腳本,我在一個名為 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,請停止腳本並返回消息)

非常感謝你們! 祝你有美好的一天

您可以使用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');
  });
});

此方法將僅替換第一個匹配的單詞。 如果要替換所有匹配的單詞,作為第一個參數,可以使用正則表達式。 字符g代表全局, m代表多行。

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

data.replace(regex, '');

如果要測試文件是否包含請求的單詞,可以使用.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