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?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fs
- Keeping track of variable instances
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).
You can use the
fs.readdir
orfs.readdirSync
methods.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 the most convinient 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)
Use
npm
list-contents module. It reads the contents and sub-contents of the given directory and returns the list of files' and folders' paths.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.
Get
sorted
filenames. You can filter results based on a specificextension
such as'.txt'
,'.jpg'
and so on.