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

后端 未结 25 1164
天涯浪人
天涯浪人 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:26

    Get sorted filenames. You can filter results based on a specific extension such as '.txt', '.jpg' and so on.

    import * as fs from 'fs';
    import * as Path from 'path';
    
    function getFilenames(path, extension) {
        return fs
            .readdirSync(path)
            .filter(
                item =>
                    fs.statSync(Path.join(path, item)).isFile() &&
                    (extension === undefined || Path.extname(item) === extension)
            )
            .sort();
    }
    

提交回复
热议问题