我试图使用Node.js获取目录中所有文件的名称列表。我希望输出文件名数组。我该怎么做?


当前回答

我通常使用:FS Extra。

const fileNameArray = Fse.readdir('/some/path');

结果:

[
  "b7c8a93c-45b3-4de8-b9b5-a0bf28fb986e.jpg",
  "daeb1c5b-809f-4434-8fd9-410140789933.jpg"
]

其他回答

我最近为此开发了一个工具,它可以做到这一点。。。它异步获取目录并返回项目列表。您可以获取目录、文件或两者,首先是文件夹。如果不想获取整个文件夹,也可以对数据进行分页。

https://www.npmjs.com/package/fs-browser

这是链接,希望它能帮助到某人!

这将起作用,并将结果存储在test.txt文件中,该文件将位于同一目录中

  fs.readdirSync(__dirname).forEach(file => {
    fs.appendFileSync("test.txt", file+"\n", function(err){
    })
})

加载fs:

const fs = require('fs');

异步读取文件:

fs.readdir('./dir', function (err, files) {
    // "files" is an Array with files names
});

读取文件同步:

var files = fs.readdirSync('./dir');

这是一个TypeScript,可选递归,可选错误日志和异步解决方案。可以为要查找的文件名指定正则表达式。

我使用了fs extra,因为这是对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<string[]>}
 * @memberof FileHelper
 */
public static async findFiles(
    folder: string,
    filePattern: string = '.*',
    errors: Error[] | undefined = undefined,
    folderDepth: number = 0
): Promise<string[]> {
    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
}

但是,上面的答案不会对目录执行递归搜索。以下是我对递归搜索所做的操作(使用node walk:npm install walk)

var walk    = require('walk');
var files   = [];

// Walker options
var walker  = walk.walk('./test', { followLinks: false });

walker.on('file', function(root, stat, next) {
    // Add this file to the list of files
    files.push(root + '/' + stat.name);
    next();
});

walker.on('end', function() {
    console.log(files);
});