Get all files recursively in directories NodejS

前端 未结 10 1272
暖寄归人
暖寄归人 2020-12-14 07:15

I have a little problem with my function. I would like to get all files in many directories. Currently, I can retrieve the files in the file passed in parameters. I would li

10条回答
  •  猫巷女王i
    2020-12-14 07:30

    I've seen many very long answers, and it's kinda a waste of memory space. Some also use packages like glob, but if you don't want to depend on any package, here's my solution.

    const Path = require("path");
    const FS   = require("fs");
    let Files  = [];
    
    function ThroughDirectory(Directory) {
        FS.readdirSync(Directory).forEach(File => {
            const Absolute = Path.join(Directory, File);
            if (FS.statSync(Absolute).isDirectory()) return ThroughDirectory(Absolute);
            else return Files.push(Absolute);
        });
    }
    
    ThroughDirectory("./input/directory/");
    

    It's pretty self-explanatory. There's an input directory, and it iterates through that. If one of the items is also a directory, go through that and so on. If it's a file, add the absolute path to the array.

    Hope this helped :]

提交回复
热议问题