read all file using fspromises in typescript

To read all files using fs.promises in TypeScript, you can follow these steps:

  1. Import the fs module and promises property from the module:

    index.ts
    import { promises as fsPromises } from 'fs';
    
    45 chars
    2 lines
  2. Define an async function to read all files in a directory:

    index.ts
    async function readAllFiles(directoryPath: string): Promise<string[]> {
      try {
        const files = await fsPromises.readdir(directoryPath);
        const fileContents = await Promise.all(
          files.map(async (file) => {
            const filePath = `${directoryPath}/${file}`;
            const content = await fsPromises.readFile(filePath, 'utf-8');
            return content;
          })
        );
        return fileContents;
      } catch (error) {
        console.error('Error reading files:', error);
        return [];
      }
    }
    
    496 chars
    17 lines
  3. Call the readAllFiles function and pass the directory path as an argument:

    index.ts
    const directoryPath = '/path/to/files';
    readAllFiles(directoryPath)
      .then((fileContents) => {
        console.log('Read all files successfully!');
        console.log(fileContents);
      })
      .catch((error) => {
        console.error('Error:', error);
      });
    
    245 chars
    10 lines

Make sure to replace /path/to/files with the actual directory path you want to read files from.

Note: This code uses async/await syntax to handle asynchronous operations. Ensure that your TypeScript project is set up to support ECMAScript target version of ES2017 or later, and that you have the necessary type definitions for the fs module installed.

related categories

gistlibby LogSnag