To loop over files and read them async in TypeScript, you can use the fs
module provided by Node.js. First, import the fs
module and use the readdir
method to get an array of file names from a directory. Then, use a for...of
loop to loop over the file names, and use the readFile
method to read each file asynchronously.
Here's an example:
index.ts364 chars14 lines
In this example, the readFilesAsync
function first uses readdir
to get an array of file names from the directory /path/to/directory
. It then loops over the file names using a for...of
loop, and for each file, uses readFile
to read the file's contents asynchronously. Finally, it logs the contents of each file to the console.
Note that readFile
takes a second argument, which specifies the encoding of the file's contents. In this example, the encoding is set to utf-8
, which means the contents will be returned as a string. If you want to read the file as binary data, you can omit the second argument or set it to null
.
gistlibby LogSnag