I wondering if it's possible to open a text file with javascript (location something like: http://mysite.com/directory/file.txt) and check if the file contains a given string/variable.
In php this can be accomplished very easy with something like:
$file = file_get_contents("filename.ext");
if (!strpos($file, "search string")) {
echo "String not found!";
} else {
echo "String found!";
}
Is there a, preferably easy, way to do this? (I'm running the "function" in a .js file on nodejs, appfog, if it might be necessarily).
You can not open files client side with javascript.
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)
}
});
Is there a, preferably easy, way to do this?
Yes.
require("fs").readFile("filename.ext", function(err, cont) {
if (err)
throw err;
console.log("String"+(cont.indexOf("search string")>-1 ? " " : " not ")+"found");
});
You may also consider to use a stream, because it can handle larger files.
```
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);
});
```
Error or close will occur, it will then close the stream becasue autoClose is true, the default vallue.