Home > Enterprise >  matching file format using glob in nodejs
matching file format using glob in nodejs

Time:06-06

I am not able to show message 'File not found !' using glob . here I am using glob to matching file format. if file is available in the directory it is working fine. but if not available it is nothing showing 'file not found'. I noticed that if condition if (err) is always false , so that it always shows 'File found' whether it is available or not !

const glob = require('glob');

value1='./**/**.NIC.2*'  //file format like 

if (value1){
    const fs = require("fs");
    glob(value1, function (err, files) {
        
         if (err) {
             console.log('File Not Found !');
           }
         else  { 
                files.forEach(path => {
                   console.log('File  Found !');
                   console.log('File Path => '  path);
                   var lineReader = require('readline').createInterface({
                    input: require('fs').createReadStream(path),
                   });
                   var lineCounter = 0; var wantedLines = [];
                   lineReader.on('line', function (line) {
                     lineCounter  ;
                     wantedLines.push(line);
                     if(lineCounter==1){
                         lineReader.close();}
                    });
                   lineReader.on('close', function() {
                     var obj = wantedLines;
                     a=JSON.stringify(obj);
                     b=a.replace(/\s/g, "");
                     function2(b);
                    });
        });       
    }});

}

CodePudding user response:

It's not an error when the pattern doesn't match anything. If you want to check if the pattern didn't match any files, you should check the length of the files argument. If it's zero, then there were no matches and you can act accordingly.

if (err) {
  console.error('An error occurred!', e);
} else if (files.length === 0) {
  console.log('File Not Found !');
} else {
  files.forEach(…)
}
  • Related