如何在JavaScript中检查文件是否包含字符串或变量?

37

使用JavaScript(位置像http://example.com/directory/file.txt)打开文本文件并检查该文件是否包含给定的字符串/变量,这是否可能?

在PHP中可以轻松地完成此操作,例如:

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

有没有办法做到这一点?我在使用Node.js、appfog运行一个.js文件中的“function”。

5个回答

51

使用 JavaScript 无法在客户端打开文件。

但是,您可以在服务器端使用 Node.js 打开文件。

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

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

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

15
您还可以使用流。它们可以处理更大的文件。例如:

You can also use a stream. They can handle larger files. For example:


var fs = require('fs');
var stream = fs.createReadStream(path);
var found = false;

stream.on('data',function(d){
  if(!found) found=!!(''+d).match(content)
});

stream.on('error',function(err){
    then(err, found);
});

stream.on('close',function(err){
    then(err, found);
});

将会发生“error”或“close”中的一个。然后,流将关闭,因为autoClose的默认值为true。


由于我无法编辑我的评论,文档链接为https://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options - user4466350

2
有没有一种,最好是简单的方法来做这件事呢?
有。
require("fs").readFile("filename.ext", function(err, cont) {
    if (err)
        throw err;
    console.log("String"+(cont.indexOf("search string")>-1 ? " " : " not ")+"found");
});

1
你需要将zip创建放在“readFile”的回调函数中,或者改用“readFileSync”。 - Bergi

1
面向对象编程方式:

var JFile=require('jfile');
var txtFile=new JFile(PATH);
var result=txtFile.grep("word") ;
 //txtFile.grep("word",true) -> Add 2nd argument "true" to ge index of lines which contains "word"/

要求:

npm install jfile

简介:

((JFile)=>{
      var result= new JFile(PATH).grep("word");
})(require('jfile'))

-1

从客户端方面来看,你绝对可以做到这一点:

var xhttp = new XMLHttpRequest(), searchString = "foobar";

xhttp.onreadystatechange = function() {

  if (xhttp.readyState == 4 && xhttp.status == 200) {

      console.log(xhttp.responseText.indexOf(searchString) > -1 ? "has string" : "does not have string")

  }
};

xhttp.open("GET", "http://somedomain.io/test.txt", true);
xhttp.send();

如果您想在服务器端使用node.js进行操作,请这样使用文件系统包:
var fs = require("fs"), searchString = "somestring";

fs.readFile("somefile.txt", function(err, content) {

    if (err) throw err;

     console.log(content.indexOf(searchString)>-1 ? "has string" : "does not have string")

});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接