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.ts434 chars25 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