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

后端 未结 25 1711
天涯浪人
天涯浪人 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: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"]
    

提交回复
热议问题