30

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

これを行う方法はありますか?.jsNode.js、appfogで「関数」をファイルで実行しています。

4

5 に答える 5

41

クライアント側で 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)
  }
});
于 2013-07-03T13:23:41.027 に答える
11

ストリームを使用することもできます。より大きなファイルを処理できます。例えば:

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 であるため、ストリームが閉じます。

于 2015-05-14T16:25:31.247 に答える
2

これを行うための、できれば簡単な方法はありますか?

はい。

require("fs").readFile("filename.ext", function(err, cont) {
    if (err)
        throw err;
    console.log("String"+(cont.indexOf("search string")>-1 ? " " : " not ")+"found");
});
于 2013-07-03T13:26:03.543 に答える
-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")

});
于 2016-07-03T17:50:30.720 に答える