How do you get a list of the names of all files present in a directory in Node.js?

后端 未结 25 1236
天涯浪人
天涯浪人 2020-11-22 07:47

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?

相关标签:
25条回答
  • 2020-11-22 08:26

    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:

    const fs = require('fs');
    const path = require('path');
    
    fs.readdirSync('your-directory-path')
      .filter((file) => fs.lstatSync(path.join(folder, file)).isFile());
    
    0 讨论(0)
  • 2020-11-22 08:26

    Get sorted filenames. You can filter results based on a specific extension such as '.txt', '.jpg' and so on.

    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();
    }
    
    0 讨论(0)
  • 2020-11-22 08:27

    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!

    0 讨论(0)
  • 2020-11-22 08:28

    I usually use: FS-Extra.

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

    Result:

    [
      "b7c8a93c-45b3-4de8-b9b5-a0bf28fb986e.jpg",
      "daeb1c5b-809f-4434-8fd9-410140789933.jpg"
    ]
    
    0 讨论(0)
  • 2020-11-22 08:30

    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

    npm install glob
    

    Then use wild card to match filenames (example taken from package's website)

    var glob = require("glob")
    
    // options is optional
    glob("**/*.js", options, function (er, files) {
      // files is an array of filenames.
      // If the `nonull` option is set, and nothing
      // was found, then files is ["**/*.js"]
      // er is an error object or null.
    })
    
    0 讨论(0)
  • 2020-11-22 08:30

    I'm assuming from your question that you don't want directories names, just files.

    Directory Structure Example

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

    Walk function

    Credits go to Justin Maier in this gist

    If you want just an array of the files paths use 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), []);
    }
    

    Usage

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

    Output

    [
      "/animals/all.jpg",
      "/animals/mammals/cat.jpg",
      "/animals/mammals/dog.jpg",
      "/animals/insects/bee.jpg"
    ];
    
    0 讨论(0)
提交回复
热议问题