如何获取 Node.js 目录中存在的所有文件的名称列表?
我正在尝试使用 Node.js 获取目录中存在的所有文件的名称列表。我想要的输出是文件名数组。我该怎么做?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我正在尝试使用 Node.js 获取目录中存在的所有文件的名称列表。我想要的输出是文件名数组。我该怎么做?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(30)
这是一个异步递归版本。
Here's an asynchronous recursive version.
采用@Hunan-Rostomyan 的一般方法,使其更加简洁并添加了
excludeDirs
参数。使用includeDirs
进行扩展很简单,只需遵循相同的模式即可:示例用法:
Took the general approach of @Hunan-Rostomyan, made it a litle more concise and added
excludeDirs
argument. It'd be trivial to extend withincludeDirs
, just follow same pattern:Example usage:
我通常使用:FS-Extra。
结果:
I usually use: FS-Extra.
Result:
使用基于 Promise 的 fs api 的当前最上面列出的答案是:
The modern (Node 21) version of the current top listed answer using the promise-based fs api is:
请注意:如果您计划对目录中的每个文件执行操作,请尝试 vinyl-fs< /a> (由流构建系统 gulp 使用)。
Just a heads up: if you're planning to perform operations on each file in a directory, try vinyl-fs (which is used by gulp, the streaming build system).
这将起作用并将结果存储在 test.txt 文件中,该文件将出现在同一目录中
This will work and store the result in test.txt file which will be present in the same directory
我最近为此构建了一个工具,它可以异步获取目录并返回项目列表。您可以获取目录、文件或两者,其中文件夹优先。如果您不想获取整个文件夹,您还可以对数据进行分页。
https://www.npmjs.com/package/fs-browser
这是链接,希望对某人有帮助!
I've recently built a tool for this that does just this... It fetches a directory asynchronously and returns a list of items. You can either get directories, files or both, with folders being first. You can also paginate the data in case where you don't want to fetch the entire folder.
https://www.npmjs.com/package/fs-browser
This is the link, hope it helps someone!
没有 npm 安装。这适用于启动终端的当前文件夹,但您可以将 process.cwd() 更改为另一个文件夹。享受!
No npm install. This works for the current folder where you launch the terminal, but you can change
process.cwd()
to another folder. Enjoy!我制作了一个节点模块来自动执行此任务: mddir
使用
节点 mddir "../relative/ path/"
要安装: npm install mddir -g
要为当前目录生成 markdown:mddir
要为任何绝对路径生成:mddir /absolute/path
要为相对路径生成:mddir ~/Documents/whatever。
md 文件将在您的工作目录中生成。
目前忽略 node_modules 和 .git 文件夹。
故障排除
如果您收到错误“node\r:没有这样的文件或目录”,则问题是您的操作系统使用不同的行结束符,并且如果您未将行结束样式显式设置为 Unix,则 mddir 无法解析它们。这通常会影响 Windows,但也会影响某些版本的 Linux。将行结尾设置为 Unix 样式必须在 mddir npm 全局 bin 文件夹中执行。
行结尾修复
获取 npm bin 文件夹路径:
npm config get prefix
Cd 进入该文件夹
brew install dos2unix
dos2unix lib/node_modules/mddir/src/mddir.js
这会将行结尾转换为 Unix 而不是 Dos
然后正常运行:node mddir "../relative/path/"。
生成的 Markdown 文件结构“directoryList.md”示例
I made a node module to automate this task: mddir
Usage
node mddir "../relative/path/"
To install: npm install mddir -g
To generate markdown for current directory: mddir
To generate for any absolute path: mddir /absolute/path
To generate for a relative path: mddir ~/Documents/whatever.
The md file gets generated in your working directory.
Currently ignores node_modules, and .git folders.
Troubleshooting
If you receive the error 'node\r: No such file or directory', the issue is that your operating system uses different line endings and mddir can't parse them without you explicitly setting the line ending style to Unix. This usually affects Windows, but also some versions of Linux. Setting line endings to Unix style has to be performed within the mddir npm global bin folder.
Line endings fix
Get npm bin folder path with:
npm config get prefix
Cd into that folder
brew install dos2unix
dos2unix lib/node_modules/mddir/src/mddir.js
This converts line endings to Unix instead of Dos
Then run as normal with: node mddir "../relative/path/".
Example generated markdown file structure 'directoryList.md'
如果上述许多选项看起来太复杂或不是您正在寻找的,那么这里是使用 node-dir 的另一种方法 - https://github.com/fshost/node-dir
这是一个简单的函数,用于列出在子目录中搜索的所有 .xml 文件
If many of the above options seem too complex or not what you are looking for here is another approach using node-dir - https://github.com/fshost/node-dir
Here is a somple function to list all .xml files searching in subdirectories
您可以使用
fs.readdir
或fs.readdirSync
方法。fs
包含在 Node.js 核心中,因此无需安装任何东西。fs.readdir
fs.readdirSync
两种方法之间的区别在于,第一种方法是异步的,因此您必须提供一个回调函数,该函数将在读取时执行过程结束。
第二个是同步的,它将返回文件名数组,但它将停止代码的任何进一步执行,直到读取过程结束。
You can use the
fs.readdir
orfs.readdirSync
methods.fs
is included in Node.js core, so there's no need to install anything.fs.readdir
fs.readdirSync
The difference between the two methods, is that the first one is asynchronous, so you have to provide a callback function that will be executed when the read process ends.
The second is synchronous, it will return the file name array, but it will stop any further execution of your code until the read process ends.
IMO 完成此类任务的最方便方法是使用 glob 工具。这是 Node.js 的 glob 包。安装
然后使用通配符来匹配文件名(示例取自包的 网站)
如果您打算这里是使用 globby 查找当前文件夹下的任何 xml 文件的示例
IMO the most convenient way to do such tasks is to use a glob tool. Here's a glob package for node.js. Install with
Then use wild card to match filenames (example taken from package's website)
If you are planning on using globby here is an example to look for any xml files that are under current folder
从 Node v10.10.0 开始,可以对 withFileTypes 选项>
fs.readdir
和fs.readdirSync< /code>
与
dirent.isDirectory()
结合使用 函数用于过滤目录中的文件名。看起来像这样:返回的数组的形式为:
As of Node v10.10.0, it is possible to use the new
withFileTypes
option forfs.readdir
andfs.readdirSync
in combination with thedirent.isDirectory()
function to filter for filenames in a directory. That looks like this:The returned array is in the form:
不过,上面的答案不会对目录执行递归搜索。这是我为递归搜索所做的事情(使用 node-walk:
npm install walk< /代码>)
The answer above does not perform a recursive search into the directory though. Here's what I did for a recursive search (using node-walk:
npm install walk
)获取所有子目录下的文件
Get files in all subdirs
这是一个简单的解决方案,仅使用本机
fs
和path
模块:或异步版本(使用
fs.readdir
代替):然后您只需调用 (对于同步版本):
或异步版本:
区别在于节点在执行 IO 时如何阻塞。鉴于上面的 API 是相同的,您可以只使用异步版本来确保最大性能。
然而,使用同步版本有一个优点。步行完成后立即执行某些代码会更容易,如步行后的下一条语句。对于异步版本,您需要一些额外的方法来了解何时完成。也许首先创建所有路径的地图,然后枚举它们。对于简单的构建/util 脚本(相对于高性能 Web 服务器),您可以使用同步版本而不会造成任何损坏。
Here's a simple solution using only the native
fs
andpath
modules:or async version (uses
fs.readdir
instead):Then you just call (for sync version):
or async version:
The difference is in how node blocks while performing the IO. Given that the API above is the same, you could just use the async version to ensure maximum performance.
However there is one advantage to using the synchronous version. It is easier to execute some code as soon as the walk is done, as in the next statement after the walk. With the async version, you would need some extra way of knowing when you are done. Perhaps creating a map of all paths first, then enumerating them. For simple build/util scripts (vs high performance web servers) you could use the sync version without causing any damage.
在 ES7 中使用 Promises 与
mz/fs 异步使用
mz
模块提供了核心的 Promisified 版本节点库。使用它们很简单。首先安装库...然后...
或者您可以将它们编写在 ES7 中的异步函数中:
更新递归列表
一些用户指定希望查看递归列表(尽管不在问题中)...使用
fs-promise
。它是mz
的薄包装。然后...
Using Promises with ES7
Asynchronous use with mz/fs
The
mz
module provides promisified versions of the core node library. Using them is simple. First install the library...Then...
Alternatively you can write them in asynchronous functions in ES7:
Update for recursive listing
Some of the users have specified a desire to see a recursive listing (though not in the question)... Use
fs-promise
. It's a thin wrapper aroundmz
.then...
非递归版本
您没有说您想递归地执行此操作,因此我假设您只需要目录的直接子级。
示例代码:
non-recursive version
You don't say you want to do it recursively so I assume you only need direct children of the directory.
Sample code:
依赖关系。
定义。
用法。
请注意,
fileList
过于乐观。对于任何严重的问题,添加一些错误处理。Dependencies.
Definition.
Usage.
Please note that
fileList
is way too optimistic. For anything serious, add some error handling.我从你的问题假设你不需要目录名称,只需要文件。
目录结构示例
Walk
函数积分转到 Justin Maier in 此要点
如果您只需要文件路径的数组,请使用
return_object: false
:使用
输出
I'm assuming from your question that you don't want directories names, just files.
Directory Structure Example
Walk
functionCredits go to Justin Maier in this gist
If you want just an array of the files paths use
return_object: false
:Usage
Output
它只有 2 行代码:
图片:
its just 2 lines of code:
Image:
加载
fs
:读取文件异步:
读取文件同步:
Load
fs
:Read files async:
Read files sync:
如果有人仍在搜索这个,我会这样做:
它的工作对我来说非常好
if someone still search for this, i do this:
and its work very good for me
我的单行代码:
My one liner code:
获取
排序
文件名。您可以根据特定的扩展名
过滤结果,例如'.txt'
、'.jpg'
等。Get
sorted
filenames. You can filter results based on a specificextension
such as'.txt'
,'.jpg'
and so on.如果有人:
只想列出项目中本地子文件夹中的文件名(不包括目录),
My 2 cents if someone:
Just want to list file names (excluding directories) from a local sub-folder on their project
试试这个,它对我有用
Try this, it works for me
这是一个 TypeScript,可选递归,可选错误日志记录和异步解决方案。您可以为要查找的文件名指定正则表达式。
我使用了
fs-extra
,因为它是对fs
的简单超级集改进。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 onfs
.使用 flatMap:
给定以下目录:
用途:
输出:
Using flatMap:
Given the following directory:
Usage:
Output:
开箱即用
如果您想要一个开箱即用的具有目录结构的对象,我强烈建议您检查目录树。
假设您有以下结构:
将返回:
自定义对象
否则,如果您想使用自定义设置创建目录树对象,请查看以下代码片段。在此 codesandbox。
然后你可以简单地执行以下操作:
Out of the box
In case you want an object with the directory structure out-of-the-box I highly reccomend you to check directory-tree.
Lets say you have this structure:
Will return:
Custom Object
Otherwise if you want to create an directory tree object with your custom settings have a look at the following snippet. A live example is visible on this codesandbox.
Then you can simply do: