How can I check if a file contains a string or a variable in JavaScript?
OOP way :
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"/
Requirement :
npm install jfile
Brief :
((JFile)=>{
var result= new JFile(PATH).grep("word");
})(require('jfile'))
You can also use a stream. They can handle larger files. For example:
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);
});
Either an 'error' or 'close' will occur. Then, the stream will close since the default value of autoClose is true.
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) //Do Things
}
});
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)
}
});
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");
});