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

To list all the files in the current directory and all subdirectories in TypeScript, we first need to import the fs module, which provides access to the file system. We also need to use the readdir function to read the contents of a directory. To recursively traverse subdirectories, we can call the function on each subdirectory we encounter.

Here's the code:

index.ts
import fs from 'fs';

function listFiles(dir: string) {
  fs.readdir(dir, (err, files) => {
    if (err) throw err;

    files.forEach(file => {
      const filePath = `${dir}/${file}`;

      fs.stat(filePath, (err, stat) => {
        if (err) throw err;

        if (stat.isDirectory()) {
          listFiles(filePath);
        } else {
          console.log(filePath);
        }
      });
    });
  });
}

// usage
listFiles('.');
434 chars
25 lines

In this code, the listFiles function takes a directory path as its argument, reads its contents using fs.readdir, and iterates over each file in the directory. For each file, we get its full path by concatenating the directory path and file name, and then call fs.stat to check whether the file is a directory or a regular file. If it's a directory, we recursively call the listFiles function with the path of the subdirectory. If it's a file, we simply log its path to the console.

To list the files in the current directory and all subdirectories, we call listFiles with '.', which represents the current directory.

gistlibby LogSnag