How do you get a list of the names of all files present in a directory in Node.js?

后端 未结 25 1682
天涯浪人
天涯浪人 2020-11-22 07:47

I\'m trying to get a list of the names of all the files present in a directory using Node.js. I want output that is an array of filenames. How can I do this?

25条回答
  •  温柔的废话
    2020-11-22 08:16

    Took the general approach of @Hunan-Rostomyan, made it a litle more concise and added excludeDirs argument. It'd be trivial to extend with includeDirs, just follow same pattern:

    import * as fs from 'fs';
    import * as path from 'path';
    
    function fileList(dir, excludeDirs?) {
        return fs.readdirSync(dir).reduce(function (list, file) {
            const name = path.join(dir, file);
            if (fs.statSync(name).isDirectory()) {
                if (excludeDirs && excludeDirs.length) {
                    excludeDirs = excludeDirs.map(d => path.normalize(d));
                    const idx = name.indexOf(path.sep);
                    const directory = name.slice(0, idx === -1 ? name.length : idx);
                    if (excludeDirs.indexOf(directory) !== -1)
                        return list;
                }
                return list.concat(fileList(name, excludeDirs));
            }
            return list.concat([name]);
        }, []);
    }
    

    Example usage:

    console.log(fileList('.', ['node_modules', 'typings', 'bower_components']));
    

提交回复
热议问题