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

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

    This is a TypeScript, optionally recursive, optionally error logging and asynchronous solution. You can specify a regular expression for the file names you want to find.

    I used fs-extra, because its an easy super set improvement on fs.

    import * as FsExtra from 'fs-extra'
    
    /**
     * Finds files in the folder that match filePattern, optionally passing back errors .
     * If folderDepth isn't specified, only the first level is searched. Otherwise anything up
     * to Infinity is supported.
     *
     * @static
     * @param {string} folder The folder to start in.
     * @param {string} [filePattern='.*'] A regular expression of the files you want to find.
     * @param {(Error[] | undefined)} [errors=undefined]
     * @param {number} [folderDepth=0]
     * @returns {Promise}
     * @memberof FileHelper
     */
    public static async findFiles(
        folder: string,
        filePattern: string = '.*',
        errors: Error[] | undefined = undefined,
        folderDepth: number = 0
    ): Promise {
        const results: string[] = []
    
        // Get all files from the folder
        let items = await FsExtra.readdir(folder).catch(error => {
            if (errors) {
                errors.push(error) // Save errors if we wish (e.g. folder perms issues)
            }
    
            return results
        })
    
        // Go through to the required depth and no further
        folderDepth = folderDepth - 1
    
        // Loop through the results, possibly recurse
        for (const item of items) {
            try {
                const fullPath = Path.join(folder, item)
    
                if (
                    FsExtra.statSync(fullPath).isDirectory() &&
                    folderDepth > -1)
                ) {
                    // Its a folder, recursively get the child folders' files
                    results.push(
                        ...(await FileHelper.findFiles(fullPath, filePattern, errors, folderDepth))
                    )
                } else {
                    // Filter by the file name pattern, if there is one
                    if (filePattern === '.*' || item.search(new RegExp(filePattern, 'i')) > -1) {
                        results.push(fullPath)
                    }
                }
            } catch (error) {
                if (errors) {
                    errors.push(error) // Save errors if we wish
                }
            }
        }
    
        return results
    }
    

提交回复
热议问题