Javascript-添加所有文件扩展名

时间:2018-02-02 13:16:37

标签: javascript node.js filenames

我希望我在这里搜索的代码也按文件名搜索,给定的情况当然是显示文件夹和子文件夹中以TXT结尾的所有文件。 我很乐意知道正确的命令:

谢谢

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');

1 个答案:

答案 0 :(得分:1)

我对您的代码进行了一些更改,我认为它现在可以正常运行:

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]);

更新:代码已更改为遵循要求更改。