list all the files in the current directory and all subdirectories and print the full path to the fil in javascript

Here is a solution using Node.js and the built-in File System (fs) module:

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

function listFiles(dir) {
  // Get a list of all files in the directory
  const files = fs.readdirSync(dir);

  // Loop through each file
  files.forEach(file => {
    // Get the full path of the file
    const filePath = path.join(dir, file);

    // Check if the file is a directory
    if (fs.statSync(filePath).isDirectory()) {
      // Recursively list files in the subdirectory
      listFiles(filePath);
    } else {
      // Print the full path to the file
      console.log(filePath);
    }
  });
}

// Call the function with the current directory
listFiles('./');
631 chars
26 lines

This function takes a directory path as an argument and uses fs.readdirSync to get a list of all files in the directory. It then loops through each file and checks if it is a directory using fs.statSync. If it is a directory, it recursively calls the function with the subdirectory path. If it is a file, it prints the full path to the console using console.log and path.join.

Note that fs.readdirSync is a synchronous function and will block the event loop until it completes, so this solution may not be suitable for very large directories. In that case, you can use the asynchronous version fs.readdir and refactor the function to use promises or callbacks.

gistlibby LogSnag