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


当前回答

这是一个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
}

其他回答

我从你的问题中假设你不需要目录名,只需要文件。

目录结构示例

animals
├── all.jpg
├── mammals
│   └── cat.jpg
│   └── dog.jpg
└── insects
    └── bee.jpg

步行功能

根据这一要点,Justin Maier将获得积分

如果只需要一个文件路径数组,请使用return_object:false:

const fs = require('fs').promises;
const path = require('path');

async function walk(dir) {
    let files = await fs.readdir(dir);
    files = await Promise.all(files.map(async file => {
        const filePath = path.join(dir, file);
        const stats = await fs.stat(filePath);
        if (stats.isDirectory()) return walk(filePath);
        else if(stats.isFile()) return filePath;
    }));

    return files.reduce((all, folderContents) => all.concat(folderContents), []);
}

用法

async function main() {
   console.log(await walk('animals'))
}

输出

[
  "/animals/all.jpg",
  "/animals/mammals/cat.jpg",
  "/animals/mammals/dog.jpg",
  "/animals/insects/bee.jpg"
];

如果上面的许多选项看起来太复杂,或者不是您想要的,这里是另一种使用node-dir的方法https://github.com/fshost/node-dir

npm install node-dir

下面是一个somple函数,用于列出在子目录中搜索的所有.xml文件

import * as nDir from 'node-dir' ;

listXMLs(rootFolderPath) {
    let xmlFiles ;

    nDir.files(rootFolderPath, function(err, items) {
        xmlFiles = items.filter(i => {
            return path.extname(i) === '.xml' ;
        }) ;
        console.log(xmlFiles) ;       
    });
}

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

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

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

使用npm列表内容模块。它读取给定目录的内容和子内容,并返回文件和文件夹路径列表。

const list = require('list-contents');

list("./dist",(o)=>{
  if(o.error) throw o.error;
   console.log('Folders: ', o.dirs);
   console.log('Files: ', o.files);
});

获取排序的文件名。您可以基于特定扩展名(如“.txt”、“.jpg”等)过滤结果。

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();
}