如何在JavaScript中检查文件是否包含字符串或变量? [英] How can I check if a file contains a string or a variable in JavaScript?
问题描述
是否可以使用JavaScript打开文本文件(位置类似 http://example.com/directory/file.txt ),然后检查文件中是否包含给定字符串/变量?
Is it possible to open a text file with JavaScript (location like http://example.com/directory/file.txt) and check if the file contains a given string/variable?
在PHP中,可以通过类似以下操作轻松实现:
In PHP this can be accomplished easily with something like:
$file = file_get_contents("filename.ext");
if (!strpos($file, "search string")) {
echo "String not found!";
} else {
echo "String found!";
}
有没有办法做到这一点?我正在运行功能"在带有Node.js,appfog的 .js
文件中.
Is there a way to do this? I'm running the "function" in a .js
file with Node.js, appfog.
推荐答案
您无法使用javascript打开客户端文件.
You can not open files client side with javascript.
尽管在服务器端,您也可以使用node.js来实现.
You can do it with node.js though on the server side.
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
函数,该函数可在字符串中搜索匹配项.
Newer versions of node.js (>= 6.0.0) have the includes
function, which searches for a match in a string.
fs.readFile(FILE_LOCATION, function (err, data) {
if (err) throw err;
if(data.includes('search string')){
console.log(data)
}
});
这篇关于如何在JavaScript中检查文件是否包含字符串或变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!