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

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

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

提交回复
热议问题