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

后端 未结 25 1235
天涯浪人
天涯浪人 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:18

    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).

    0 讨论(0)
  • 2020-11-22 08:18
    function getFilesRecursiveSync(dir, fileList, optionalFilterFunction) {
        if (!fileList) {
            grunt.log.error("Variable 'fileList' is undefined or NULL.");
            return;
        }
        var files = fs.readdirSync(dir);
        for (var i in files) {
            if (!files.hasOwnProperty(i)) continue;
            var name = dir + '/' + files[i];
            if (fs.statSync(name).isDirectory()) {
                getFilesRecursiveSync(name, fileList, optionalFilterFunction);
            } else {
                if (optionalFilterFunction && optionalFilterFunction(name) !== true)
                    continue;
                fileList.push(name);
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 08:21

    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.

    const list = require('list-contents');
    
    list("./dist",(o)=>{
      if(o.error) throw o.error;
       console.log('Folders: ', o.dirs);
       console.log('Files: ', o.files);
    });
    
    0 讨论(0)
  • 2020-11-22 08:22

    Load fs:

    const fs = require('fs');
    

    Read files async:

    fs.readdir('./dir', function (err, files) {
        // "files" is an Array with files names
    });
    

    Read files sync:

    var files = fs.readdirSync('./dir');
    
    0 讨论(0)
  • 2020-11-22 08:23

    Get files in all subdirs

    function getFiles (dir, files_){
        files_ = files_ || [];
        var files = fs.readdirSync(dir);
        for (var i in files){
            var name = dir + '/' + files[i];
            if (fs.statSync(name).isDirectory()){
                getFiles(name, files_);
            } else {
                files_.push(name);
            }
        }
        return files_;
    }
    
    console.log(getFiles('path/to/dir'))
    
    0 讨论(0)
  • 2020-11-22 08:25

    My 2 cents if someone:

    Just want to list file names (excluding directories) from a local sub-folder on their project

    • ✅ No additional dependencies
    • ✅ 1 function
    • ✅ Normalize path (Unix vs. Windows)
    const fs = require("fs");
    const path = require("path");
    
    /**
     * @param {string} relativeName "resources/foo/goo"
     * @return {string[]}
     */
    const listFileNames = (relativeName) => {
      try {
        const folderPath = path.join(process.cwd(), ...relativeName.split("/"));
        return fs
          .readdirSync(folderPath, { withFileTypes: true })
          .filter((dirent) => dirent.isFile())
          .map((dirent) => dirent.name.split(".")[0]);
      } catch (err) {
        // ...
      }
    };
    
    
    README.md
    package.json
    resources
     |-- countries
        |-- usa.yaml
        |-- japan.yaml
        |-- gb.yaml
        |-- provinces
           |-- .........
    
    
    listFileNames("resources/countries") #=> ["usa", "japan", "gb"]
    
    0 讨论(0)
提交回复
热议问题