find the contents of a directory in typescript

To find the contents of a directory in TypeScript, you can use the file system module that comes with Node.js. Specifically, you will need to use the readdirSync() method to read the contents of the directory synchronously.

Here is an example code block that demonstrates how to find the files in the current working directory:

index.ts
import * as fs from "fs";

const directoryPath = "./";

try {
  const files = fs.readdirSync(directoryPath);
  console.log(files);
} catch (err) {
  console.error("Error occurred while reading directory:", err);
}
214 chars
11 lines

In the above code, we first import the fs module. Then we define the directoryPath as "./" which represents the current directory. Next, in the try block, we use the readdirSync() method to read the contents of the directory and assign the result to the files variable. Finally, we log the contents of the directory to the console.

Note that if an error occurs while reading the directory, we catch the exception and log the error message to the console.

gistlibby LogSnag