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

To list all the files in the current directory and all subdirectories and print the full path to each file in TypeScript, we can use the Node.js file system module and recursion.

Here is the code:

index.ts
import fs from 'fs';
import path from 'path';

function listAllFiles(dir: string): void {
  const files = fs.readdirSync(dir);
  for (const file of files) {
    const filePath = path.join(dir, file);
    const stat = fs.statSync(filePath);
    if (stat.isDirectory()) {
      listAllFiles(filePath);
    } else {
      console.log(filePath);
    }
  }
}

listAllFiles('.');
374 chars
18 lines

This code defines a function listAllFiles that takes a directory path as an argument. It reads the content of the directory using fs.readdirSync, then iterates over the files using a for...of loop. For each file, it joins the file path with the directory path using path.join and gets its stats using fs.statSync. If the file is a subdirectory, it calls listAllFiles recursively with the subdirectory path. Otherwise, it logs the file path to the console. Finally, it calls listAllFiles with the current directory path . to list files in the current directory and all subdirectories.

gistlibby LogSnag