Recursively list all files in a directory
Sometimes you might need to get all the files in a directory as well as the sub directories. There are many ways to accomplish this task and I would like to discuss one of the ways we are using here at Walden Systems, because we believe this is the most straightforward method to recursively get all file names in a directory.
Strategy to for recursively getting all the files in a directory is straight forward and involves steps: First, we will need to import the module "fs". Second, we will use the built in function, readdirSync( ) to get the list of files and sub directories in the directory. Third, we will iterate through the list and use the built in function, statSync( ) to get the properties. Fourth, we will use the built in function, isFile( ) to check if it is a file or not. Fifth, if the item is a file, we will store it in an array, if not, we will recurse into the sub directory.
Here are the steps:
First, we will import the module fs with the following:
var filesystem = require( 'fs' ) ;
Next, we will use the function readdirSync( ) to get a list of files and directories in a given path:
var directory_listing = l_fs.readdirSync( SOME_FULL_PATH ) ;
Next, we will iterate through the list to and get the properties of each item in the list using the statSync( ) method:
for ( var item in directory_listing ) { var current_file = SOME_FULL_PATH + '/' + directory_listing[ item ] ; var status = current_file.statSync( current_file ) ; }
Next we will check if the item is a file or directory using the isFile( ) method. If it is a file, we will store it in an array, if not, we will call the function again and recurse into the directory:
if ( status.isFile( ) ) { file_list = file_list.push( current_file ) ; } else if ( status.isDirectory( ) ) { file_list = file_list.concat( FUNCTION_NAME( current_file ) ) ; }
When we put them together, we get files recursively:
var get_files_recursively = function ( SOME_FULL PATH_PARAMETER ) { var filesystem = require( 'fs' ) ; var directory_listing = l_fs.readdirSync( SOME_FULL_PATH_PARAMETER ) ; var file_list = [ ] ; for ( var item in directory_listing ) { var current_file = SOME_FULL_PATH + '/' + directory_listing[ item ] ; var status = current_file.statSync( current_file ) ; if ( status.isFile( ) ) { file_list = file_list.push( current_file ) ; } else if ( status.isDirectory( ) ) { file_list = file_list.concat( get_files_recursively ( current_file ) ) ; } } return( file_list ) ; }