是否可以使用 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
文件中运行“函数”。
您无法使用 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)
}
});
您还可以使用流。他们可以处理更大的文件。例如:
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);
});
将发生“错误”或“关闭”。然后,流将关闭,因为 autoClose 的默认值为 true。
有没有一种最好是简单的方法来做到这一点?
是的。
require("fs").readFile("filename.ext", function(err, cont) {
if (err)
throw err;
console.log("String"+(cont.indexOf("search string")>-1 ? " " : " not ")+"found");
});
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'))
从客户端你绝对可以做到这一点:
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")
});