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


当前回答

它只有2行代码:

fs=require('fs')
fs.readdir("./img/", (err,filename)=>console.log(filename))

图像:

其他回答

我制作了一个节点模块来自动化这个任务:mddir

用法

节点mddir“../relative/path/”

要安装:npm install mddir-g

为当前目录生成markdown:mddir

为任何绝对路径生成:mddir/absolute/path

为相对路径生成:mddir~/Documents/wanywhere。

md文件在您的工作目录中生成。

当前忽略node_modules和.git文件夹。

故障排除

如果您收到错误“node\r:没有这样的文件或目录”,问题是您的操作系统使用不同的行尾,如果不将行尾样式显式设置为Unix,mddir无法解析它们。这通常会影响Windows,但也会影响某些版本的Linux。必须在mddir npm全局bin文件夹中将行结尾设置为Unix样式。

线条末端固定

获取npm-bin文件夹路径:

npm配置获取前缀

Cd到该文件夹

brew安装dos2unix

dos2unix-lib/node_modules/mddir/src/mddir.js

这会将行尾转换为Unix而不是Dos

然后正常运行:node mddir“../relative/path/”。

示例生成的markdown文件结构“directoryList.md”

    |-- .bowerrc
    |-- .jshintrc
    |-- .jshintrc2
    |-- Gruntfile.js
    |-- README.md
    |-- bower.json
    |-- karma.conf.js
    |-- package.json
    |-- app
        |-- app.js
        |-- db.js
        |-- directoryList.md
        |-- index.html
        |-- mddir.js
        |-- routing.js
        |-- server.js
        |-- _api
            |-- api.groups.js
            |-- api.posts.js
            |-- api.users.js
            |-- api.widgets.js
        |-- _components
            |-- directives
                |-- directives.module.js
                |-- vendor
                    |-- directive.draganddrop.js
            |-- helpers
                |-- helpers.module.js
                |-- proprietary
                    |-- factory.actionDispatcher.js
            |-- services
                |-- services.cardTemplates.js
                |-- services.cards.js
                |-- services.groups.js
                |-- services.posts.js
                |-- services.users.js
                |-- services.widgets.js
        |-- _mocks
            |-- mocks.groups.js
            |-- mocks.posts.js
            |-- mocks.users.js
            |-- mocks.widgets.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
}

采用@湖南罗斯托米扬的一般方法,使其更加简洁,并添加了excludeDirs论点。使用includeDirs进行扩展很简单,只需遵循相同的模式:

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]);
    }, []);
}

示例用法:

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

它只有2行代码:

fs=require('fs')
fs.readdir("./img/", (err,filename)=>console.log(filename))

图像:

我通常使用:FS Extra。

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

结果:

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