find the size of a directory in typescript

To find the size of a directory in TypeScript, you can use the built-in File System (fs) module in Node.js. To do this, you can use the fs.stat() method to get the statistics of a file or directory, including its size.

Here's an example TypeScript code snippet that demonstrates how to find the size of a directory using the fs.stat() method:

index.ts
import fs from 'fs';

function getDirectorySize(dir: string): Promise<number> {
  return new Promise((resolve, reject) => {
    fs.stat(dir, (err, stats) => {
      if (err) {
        reject(err);
      } else {
        if (stats.isDirectory()) {
          let totalSize = 0;
          fs.readdir(dir, (err, files) => {
            if (err) {
              reject(err);
            } else {
              let promises = [];
              files.forEach(file => {
                promises.push(getDirectorySize(dir + '/' + file)); // Recursively call function for subdirectories
              });
              Promise.all(promises).then(subDirSizes => {
                subDirSizes.forEach(subDirSize => {
                  totalSize += subDirSize;
                });
                resolve(totalSize);
              });
            }
          });
        } else {
          resolve(stats.size); // If not a directory, return size of file
        }
      }
    });
  });
}

// Example usage
getDirectorySize('/path/to/directory').then(size => {
  console.log(`Size of directory: ${size} bytes`);
}).catch(err => {
  console.log(`Error: ${err}`);
});
1152 chars
41 lines

This TypeScript code snippet defines a getDirectorySize() function which takes a directory path as input and returns a Promise that resolves to the size of the directory in bytes.

The getDirectorySize() function uses the fs.stat() method to get the statistics of the directory. If the directory is actually a directory (and not a file), the function recursively calls itself for each subdirectory and adds up the sizes of all subdirectories. If the directory is not a directory, the function simply returns the size of the file.

To use the function, simply call it with the directory path as input and handle the resulting Promise with .then() and .catch() as demonstrated in the example usage.

gistlibby LogSnag