Проверка Javascript, если (txt) файл содержит строку/переменную
Мне интересно, можно ли открыть текстовый файл с помощью javascript (расположение: http://mysite.com/directory/file.txt) и проверить, содержит ли файл заданная строка/переменная.
В php это может быть выполнено очень легко с чем-то вроде:
$file = file_get_contents("filename.ext");
if (!strpos($file, "search string")) {
echo "String not found!";
} else {
echo "String found!";
}
Есть ли, возможно, простой способ сделать это? (Я запускаю "функцию" в файле .js на nodejs, appfog, если это может быть обязательно).
Ответы
Ответ 1
Вы не можете открыть файлы на стороне клиента с помощью JavaScript.
Вы можете сделать это с помощью node.js на стороне сервера.
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
в includes
функцию, которая ищет совпадения в строке.
fs.readFile(FILE_LOCATION, function (err, data) {
if (err) throw err;
if(data.includes('search string')){
console.log(data)
}
});
Ответ 2
Вы также можете использовать поток, потому что он может обрабатывать более крупные файлы.
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, значение по умолчанию.
Ответ 3
Есть ли, возможно, простой способ сделать это?
Да.
require("fs").readFile("filename.ext", function(err, cont) {
if (err)
throw err;
console.log("String"+(cont.indexOf("search string")>-1 ? " " : " not ")+"found");
});
Ответ 4
Способ ООП:
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'))
Ответ 5
С клиентской стороны вы можете определенно сделать это:
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")
});