find the size of a directory in javascript

To find the size of a directory in JavaScript, you can use the fs module in Node.js to work with the filesystem. Here's an example function that uses the fs module to recursively iterate through the directory and calculate its total size:

index.tsx
const fs = require('fs');
const path = require('path');

function getDirectorySize(directoryPath) {
  let totalSize = 0;
  const files = fs.readdirSync(directoryPath);

  files.forEach(function(file) {
    const filePath = path.join(directoryPath, file);
    const stats = fs.statSync(filePath);

    if (stats.isFile()) {
      totalSize += stats.size;
    } else if (stats.isDirectory()) {
      totalSize += getDirectorySize(filePath);
    }
  });

  return totalSize;
}

// Example usage
const directoryPath = 'path/to/directory';
const size = getDirectorySize(directoryPath);
console.log(`Size of ${directoryPath}: ${size} bytes`);
637 chars
26 lines

This function uses the readdirSync function to get a list of all files and directories in the directory. It then iterates through each file and directory and calculates its size using the statSync function. If the path is a file, it simply adds its size to the totalSize variable. If the path is a directory, it recursively calls the getDirectorySize function to get the size of the directory and add it to the totalSize variable.

Note that this implementation does not handle errors and may throw exceptions if there are any permission issues with accessing the directory or its contents.

gistlibby LogSnag