【问题标题】:Check for string in file using JavaScript使用 JavaScript 检查文件中的字符串
【发布时间】:2020-04-03 17:28:17
【问题描述】:

简而言之,我想要一个 javascript 函数来检查文件中的 HTML 输入。 我已经尝试按照这篇文章告诉我的方法使用:Javascript check if (txt) file contains string/variable
但一直收到错误消息说ReferenceError: fs is not defined
所以现在我在这里寻求帮助。

【问题讨论】:

标签: javascript html node.js


【解决方案1】:

我无法确定,因为您没有提供任何示例代码,但fs 通常指的是nodejs 中的“文件系统” 因此,另一个主题的答案并不完整,但它的用法暗示了导入:

var fs = require("fs")

fs.readFile(FILE_LOCATION, function (err, data) {
  if (err) throw err;
  if(data.indexOf('search string') >= 0){
   console.log(data)
  }
});

但正如其他评论者所说,这是针对 nodejs 而不是在浏览器中。

【讨论】:

  • data.includesindexOf 更直接地回答了这个问题,并且可能更高效。
  • @rayhatfield 搜索文件中的字符串(以txt文件为例)而不是字符串中的字符串。
  • @KaidenSmith 我指的是他在回调中使用indexOf,其中data 是字符串或缓冲区,两者都支持includes
【解决方案2】:

如果您尝试在浏览器中执行此操作,您可以 fetch 网址并使用 includes 来检查您要查找的字符串:

async function responseContains(url, string) {
  try {
    const content = await fetch(url).then(response => response.text());
    return content.includes(string);
  }
  catch (e) {
    console.log(e);
    throw e;
  }
}

const url = 'https://jsonplaceholder.typicode.com/todos/1';
/*
  the url above returns:
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
  }
*/

responseContains(url, 'userId')
  .then(found => console.log(`Found 'userId'? ${found}`));
// Found? true

responseContains(url, 'wookies with bananas')
  .then(found => console.log(`Found 'wookies with bananas'? ${found}`));
// Found? false

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-27
    • 2016-02-12
    • 2010-11-08
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    相关资源
    最近更新 更多