Javascript检查if(txt)文件是否包含字符串/变量

Mdl*_*dlc 15 javascript node.js

我想知道是否可以用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!";
}
Run Code Online (Sandbox Code Playgroud)

有没有,最好是简单的方法来做到这一点?(我在nodejs,appfog上的.js文件中运行"function",如果可能的话).

raa*_*m86 19

您无法使用javascript打开客户端文件.

您可以使用node.js在服务器端执行此操作.

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


mh-*_*bon 7

您还可以考虑使用流,因为它可以处理更大的文件.

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);
});
Run Code Online (Sandbox Code Playgroud)

将发生错误或关闭,然后它将关闭流,因为autoClose为true,默认值为vallue.