Javascript检查if(txt)文件是否包含字符串/变量 [英] Javascript check if (txt) file contains string/variable

查看:88
本文介绍了Javascript检查if(txt)文件是否包含字符串/变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以使用javascript打开文本文件(位置类似于: http:// mysite .com / directory / file.txt )并检查文件是否包含给定的字符串/变量。

I wondering if it's possible to open a text file with javascript (location something like: http://mysite.com/directory/file.txt) and check if the file contains a given string/variable.

在php中,这可以很容易地实现喜欢:

In php this can be accomplished very easy with something like:

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

有没有,最好是简单的方法呢? (我在nodejs,appfog上的.js文件中运行function,如果可能的话)。

Is there a, preferably easy, way to do this? (I'm running the "function" in a .js file on nodejs, appfog, if it might be necessarily).

推荐答案

您无法使用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)具有包括函数,用于搜索字符串中的匹配项。

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检查if(txt)文件是否包含字符串/变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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