Reputation: 364
I want the code which i have here to search also by file name, the given situation is of course showing all the files ending in TXT in the folder and subfolders. I would be happy to know the right command for it:
Thank you
var path = require('path'), fs=require('fs');
function fromDir(startPath,filter){
if (!fs.existsSync(startPath)){
console.log("no dir ",startPath);
return;
}
var files=fs.readdirSync(startPath);
var found = false;
for(var i=0;i<files.length;i++){
var filename=path.join(startPath,files[i]);
var stat = fs.lstatSync(filename);
if (stat.isDirectory()){
fromDir(filename,filter);
}
else if (filename.indexOf(filter)>=0) {
found = true;
console.log('-- your file was found: ',filename);
};
};
if (!found) {
console.log("nope,sorry");
}
};
fromDir('../yoyo','.txt');
Upvotes: 0
Views: 52
Reputation: 3091
I've made some changes to your code, I think it works as intended now:
const path = require('path');
const fs = require('fs');
function fromDir(startPath, filename, ext) {
if (!fs.existsSync(startPath)) {
console.log('no dir ', startPath);
return;
}
const files = fs.readdirSync(startPath);
let found = files.find(file => {
let thisFilename = path.join(startPath, file);
let stat = fs.lstatSync(thisFilename);
if (stat.isDirectory()) {
fromDir(thisFilename, filename, ext);
} else {
if (path.extname(thisFilename) === ext && path.basename(thisFilename, ext) === filename) {
return true;
}
}
})
if (found) {
console.log('-- your file was found: ', found);
}
}
fromDir('./', process.argv[3], process.argv[2]);
UPDATE: code changed to follow requirements changes.
Upvotes: 1