All files / src/utils collection.node.ts

87.87% Statements 29/33
60% Branches 6/10
100% Functions 3/3
87.87% Lines 29/33

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 7433x 33x               33x 3x       3x       3x       6x 6x 6x   6x 12x 12x   12x 9x         3x 3x       6x                 33x 2x       2x       2x 2x   2x 4x 3x 3x 1x 1x       2x    
import fs from 'fs'
import path from 'path'
import { Collection } from '../types'
 
/**
 * Creates array in the format of Collection with data loaded from directory on filesystem.
 *
 * @param dir path to the directory
 */
export async function makeCollectionFromFS(dir: string): Promise<Collection> {
  Iif (typeof dir !== 'string') {
    throw new TypeError('dir has to be string!')
  }
 
  Iif (dir === '') {
    throw new TypeError('dir must not be empty string!')
  }
 
  return buildCollectionRelative(dir, '')
}
 
async function buildCollectionRelative(dir: string, relativePath: string): Promise<Collection> {
  const dirname = path.join(dir, relativePath)
  const entries = await fs.promises.opendir(dirname)
  let collection: Collection = []
 
  for await (const entry of entries) {
    const fullPath = path.join(dir, relativePath, entry.name)
    const entryPath = path.join(relativePath, entry.name)
 
    if (entry.isFile()) {
      collection.push({
        path: entryPath,
        size: (await fs.promises.stat(fullPath)).size,
        fsPath: fullPath,
      })
    } else if (entry.isDirectory()) {
      collection = [...(await buildCollectionRelative(dir, entryPath)), ...collection]
    }
  }
 
  return collection
}
 
/**
 * Calculate folder size recursively
 *
 * @param dir the path to the folder to check
 * @returns size in bytes
 */
export async function getFolderSize(dir: string): Promise<number> {
  Iif (typeof dir !== 'string') {
    throw new TypeError('dir has to be string!')
  }
 
  Iif (dir === '') {
    throw new TypeError('dir must not be empty string!')
  }
 
  const entries = await fs.promises.opendir(dir)
  let size = 0
 
  for await (const entry of entries) {
    if (entry.isFile()) {
      const stats = await fs.promises.stat(path.join(dir, entry.name))
      size += stats.size
    } else if (entry.isDirectory()) {
      size += await getFolderSize(path.join(dir, entry.name))
    }
  }
 
  return size
}