Javascript检查(txt)文件是否包含string/variables

我想知道是否有可能打开一个JavaScript的文本文件(位置类似于: http : //mysite.com/directory/file.txt ),并检查文件是否包含给定的string/variables。

在PHP中,这可以很容易地完成,像这样的东西:

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

有没有,最好是容易的方法来做到这一点? (我在nodejs,appfog的.js文件中运行“函数”,如果可能的话)。

你不能用javascript打开文件客户端。

你可以在服务器端使用node.js来完成。

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

你也可以考虑使用stream,因为它可以处理更大的文件。

 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); }); 

错误或closures会发生,它会closuresstream,因为autoClose是true,默认值。

有没有,最好是容易的方法来做到这一点?

是。

 require("fs").readFile("filename.ext", function(err, cont) { if (err) throw err; console.log("String"+(cont.indexOf("search string")>-1 ? " " : " not ")+"found"); }); 

从客户端你绝对可以做到这一点:

 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这样做,使用File System包:

 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") }); 

OOP方式:

 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'))