为了账号安全,请及时绑定邮箱和手机立即绑定

使用 JavaScript 检查文件中的字符串

使用 JavaScript 检查文件中的字符串

神不在的星期二 2023-10-30 20:04:17
简而言之,我想要的是一个 javascript 函数来检查文件中的 HTML 输入。我尝试过按照这篇文章告诉我的那样使用:Javascript check if (txt) file contains string/variable但一直收到错误消息ReferenceError: fs is not defined,所以现在我在这里寻求帮助。
查看完整描述

2 回答

?
呼如林

TA贡献1798条经验 获得超3个赞

我无法确定,因为您没有提供任何示例代码,但fs通常指的是Node.js中的“文件系统” ,因此其他主题的答案并不完整,但导入是由其用法暗示的:

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 的,而不是在浏览器中。



查看完整回答
反对 回复 2023-10-30
?
Qyouu

TA贡献1786条经验 获得超11个赞

如果您尝试在浏览器中执行此操作,您可以获取url 并使用include来检查您要查找的字符串:

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



查看完整回答
反对 回复 2023-10-30
  • 2 回答
  • 0 关注
  • 51 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信