list all the files in the current directory and all subdirectories in javascript

You can use the built-in fs module in Node.js to list all the files in the current directory and all subdirectories recursively. Here is a sample code to achieve this:

index.tsx
const fs = require('fs');
const path = require('path');

function getFiles(dir, fileList = []) {
  const files = fs.readdirSync(dir);

  files.forEach(file => {
    const filePath = path.join(dir, file);

    if (fs.statSync(filePath).isDirectory()) {
      fileList = getFiles(filePath, fileList);
    } else {
      fileList.push(filePath);
    }
  });

  return fileList;
}

// Usage
const files = getFiles(__dirname);
console.log(files);
442 chars
23 lines

The getFiles function accepts a directory path and an optional file list array as parameters. It uses fs.readdirSync to read the contents of the directory and path.join to generate the file path.

For each file in the directory, the function checks if it's a directory or a file. If it's a directory, it calls itself recursively with the path of the subdirectory. If it's a file, it adds the file path to the file list array.

Finally, the function returns the file list array. To use this function, simply call it with the current directory path (__dirname in Node.js) and it will return an array with all the file paths in the current directory and all subdirectories.

gistlibby LogSnag