如何获取Node.js目录中存在的所有文件的名称列表?

本文翻译自:How do you get a list of the names of all files present in a directory in Node.js?

I'm trying to get a list of the names of all the files present in a directory using Node.js. 我正在尝试使用Node.js获取目录中存在的所有文件的名称列表。 I want output that is an array of filenames. 我想要输出是一个文件名数组。 How can I do this? 我怎样才能做到这一点?


#1楼

参考:https://stackoom.com/question/BRSZ/如何获取Node-js目录中存在的所有文件的名称列表


#2楼

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

#3楼

Here's an asynchronous recursive version. 这是一个异步递归版本。

    function ( path, callback){
     // the callback gets ( err, files) where files is an array of file names
     if( typeof callback !== 'function' ) return
     var
      result = []
      , files = [ path.replace( /\/\s*$/, '' ) ]
     function traverseFiles (){
      if( files.length ) {
       var name = files.shift()
       fs.stat(name, function( err, stats){
        if( err ){
         if( err.errno == 34 ) traverseFiles()
    // in case there's broken symbolic links or a bad path
    // skip file instead of sending error
         else callback(err)
        }
        else if ( stats.isDirectory() ) fs.readdir( name, function( err, files2 ){
         if( err ) callback(err)
         else {
          files = files2
           .map( function( file ){ return name + '/' + file } )
           .concat( files )
          traverseFiles()
         }
        })
        else{
         result.push(name)
         traverseFiles()
        }
       })
      }
      else callback( null, result )
     }
     traverseFiles()
    }

#4楼

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);
        }
    }
}

#5楼

只是抬头:如果您计划对目录中的每个文件执行操作,请尝试使用vinyl-fs (由gulp (流式构建系统)使用)。


#6楼

IMO the most convinient way to do such tasks is to use a glob tool. IMO最方便的方法就是使用glob工具。 Here's a glob package for node.js. 这是node.js的glob包 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 篇原创文章 · 获赞 7 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/asdfgh0077/article/details/105380919