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

后端 未结 25 1244
天涯浪人
天涯浪人 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: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.
    })
    

提交回复
热议问题