如何在JavaScript中检查文件是否包含字符串或变量? [英] How can I check if a file contains a string or a variable in JavaScript?

查看:52
本文介绍了如何在JavaScript中检查文件是否包含字符串或变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用JavaScript打开文本文件(位置类似 http://example.com/directory/file.txt ),然后检查文件中是否包含给定字符串/变量?

Is it possible to open a text file with JavaScript (location like http://example.com/directory/file.txt) and check if the file contains a given string/variable?

在PHP中,可以通过类似以下操作轻松实现:

In PHP this can be accomplished easily with something like:

$file = file_get_contents("filename.ext");
if (!strpos($file, "search string")) {
    echo "String not found!";
} else {
    echo "String found!";
}

有没有办法做到这一点?我正在运行功能"在带有Node.js,appfog的 .js 文件中.

Is there a way to do this? I'm running the "function" in a .js file with Node.js, appfog.

推荐答案

您无法使用javascript打开客户端文件.

You can not open files client side with javascript.

尽管在服务器端,您也可以使用node.js来实现.

You can do it with node.js though on the server side.

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

较新版本的node.js(> = 6.0.0)具有 includes 函数,该函数可在字符串中搜索匹配项.

Newer versions of node.js (>= 6.0.0) have the includes function, which searches for a match in a string.

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

这篇关于如何在JavaScript中检查文件是否包含字符串或变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆