Nodachisoft Nodachisoft logo, Katana Sword Icon
  
@Amaji✎ Update December-14-2021

About How to get file list under a path with inside of the subfolders with javascript on nodejs

About How to get file list under a path with inside of the subfolders with javascript on nodejs

Summury Of Article

About How to get file list under a path with inside of the subfolders with javascript on nodejs, with sample code that can be copied and pasted.

Code for getting a list of files.

The following is an example code. It retrieves the files under the specified path as an array as a list of files including subfolders.

In addition, it is possible to optionally specify the depth of the search (how deep to search for structures such as folders within folders). can be specified as an option.

The path in the sample code is described in the Windows version. However, it works well on Linux and MacOS.

 
getfilelist_recursively.js
/**
 * serach files recursively
 *  Option: you can limit search path depth.
 * @param {string} targetpath search base path
 * @param {number} depth recursive depth. by default = no depth limit
 * @returns list of absolute path of files in targetpath
 */
var GetFilelistRecursively = ((targetpath, depth = -1) => {
    let result = [];
    let dirs = fs.readdirSync(targetpath);
    dirs.forEach(file => {
        let filepath = targetpath + "/" + file;
        if ( fs.lstatSync(filepath).isDirectory()) {
            if ( depth == 0 ) return result;
            result = result.concat( GetFilelistRecursively(filepath, depth - 1));
        } else {
            result.push(filepath);
        }
    });
    return result;
});
// usage: 
console.log( GetFilelistRecursively("C:/testdir",1) );

In the above program, search the path "c:/testdir".

The second argument is set to "1" in order to limit the file search to the second level. If you want to search for files without any restriction, you can leave the second argument unspecified.

The folder structure is shown below, and the targets to be retrieved are highlighted.

filesystem_structure
C:\TESTDIR
├─ readme.txt
├─ lv1-image
│  ├─ magictexture.png
│  └─ emptyDir  <= Empty Directory
└─lv2-prog
   ├─ 3dgame.js
   ├─ main.js
   └─ package-database
       └─ index.js

The result of running the program is shown below.

Result
> node getfilelist_recursively.js
[
  'C:/testdir/lv1-image/magictexture.png',
  'C:/testdir/lv2-prog/3dgame.js',
  'C:/testdir/lv2-prog/main.js',
  'C:/testdir/readme.txt'
]

Okay, the list of files has been retrieved!

Code for getting a list of files and directories.

You may also want to get a list of files and directories.

Then, You can code like this:

 
getfilelist_recursively2.js
/**
 * serach files and directories recursively.
 *  Option: you can limit search path depth.
 * @param {string} targetpath search base path
 * @param {number} depth recursive depth. default = no depth limit
 * @returns list of { path:absolute path, isDir:is directory } of files and dirs in targetpath
 */
var GetFilelistRecursively2 = ((targetpath, depth = -1) => {
    let result = [];
    let dirs = fs.readdirSync(targetpath);
    dirs.forEach(file => {
        let filepath = targetpath + "/" + file;
        let isDir = fs.lstatSync(filepath).isDirectory();
        result.push({path:filepath, isDir:isDir });
        if ( isDir ) {
            if ( depth == 0 ) return result;
            result = result.concat( GetFilelistRecursively2(filepath, depth - 1));
        }
    });
    return result;
});
// usage: 
console.log( GetFilelistRecursively2("C:/testdir",1) );

The folder structure is shown below, and the targets to be retrieved are highlighted.

filesystem_structure
C:\TESTDIR
├─ readme.txt
├─ lv1-image
│  ├─ magictexture.png
│  └─ emptyDir  <= Empty Directory
└─lv2-prog
   ├─ 3dgame.js
   ├─ main.js
   └─ package-database
       └─ index.js

Only c:\testdir\lv2-prog\package-database\index.js is excluded because of the depth.

and the result of running the program is shown below.

Result
> node getfilelist_recursively2.js
[
  { path: 'C:/testdir/lv1-image', isDir: true },
  { path: 'C:/testdir/lv1-image/magictexture.png', isDir: false },
  { path: 'C:/testdir/lv2-prog', isDir: true },
  { path: 'C:/testdir/lv2-prog/3dgame.js',isDir: false },
  { path: 'C:/testdir/lv2-prog/main.js',isDir: false },
  { path: 'C:/testdir/readme.txt'isDir: false },
]

Cautions for use

An exception will be thrown when trying to explore a folder with insufficient permissions.

Exception_Thrown
node:internal/fs/utils:344
    throw err;
    ^

Error: EPERM: operation not permitted, lstat 'C://$Recycle.Bin/S-1-5-18'
    at Object.lstatSync (node:fs:1514:3)
    at C:\02_data\getfilelist_recursively.js:27:17

The error message is "Error: EPERM: operation not permitted, lstat XXXX". indicates that the access to path "XXXX" failed to get the status due to lack of permission.

In this example, an attempt to access the trash-bin directory failed.

Websites and references that were very helpful.

Page History

date modification
none
 
 
Message sent

Thank you for your message.

Something error has occured!

Sorry. The Error has occurred.We apologize for the inconvenience.Please try again in a few minutes or contact us via DM below.

Twitter:@NodachiSoft_eng
Name:
 
Replay To:
 
Message:
 
Back
Check the content!

Send the following information to us. If you are happy with your submission, please click "Send". If you want to modify it, please click "Back".

Name:
 
Reply To:
 
Message:
 
Enter a confirmation key to make sure that you are not operating from a Robot.
Confirmation Key is 95
Back
 / 
Go to Confirmation
Entry fields
Go to Confirmation

There are 5 articles that may be relevant!

How to pass arguments to npm run script

How to pass arguments to npm run script

#Nodejs#Javascript✎ 2021-12-16
Describe how to pass argument to npm run script.
Table Of Contents
About How to get file list under a path with inside of the subfolders with javascript on nodejs
About How to get file list under a path with inside of the subfolders with javascript on nodejs
Summury Of Article
Summury Of Article
Code for getting a list of files.
Code for getting a list of files.
Code for getting a list of files and directories.
Code for getting a list of files and directories.
Cautions for use
Cautions for use
Websites and references that were very helpful.
Websites and references that were very helpful.
Page History
Page History
Nodachisoft © 2021