Skip to content

Commit

Permalink
make file-size-builder thenable
Browse files Browse the repository at this point in the history
  • Loading branch information
marcuspoehls committed Oct 4, 2023
1 parent 4d68b07 commit 9ea6c02
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 7 deletions.
19 changes: 16 additions & 3 deletions src/file-size-resolver.ts → src/file-size-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,15 @@

import Fs from 'fs-extra'

export type FileSizeMetric = 'bytes' | 'kilobytes' | 'megabytes' | 'gigabytes' | 'terabytes' | 'petabytes'

export class FileSizeResolver {
export type FileSizeMetric =
'bytes' |
'kilobytes' |
'megabytes' |
'gigabytes' |
'terabytes' |
'petabytes'

export class FileSizeBuilder {
/**
* Stores the file size metric.
*/
Expand Down Expand Up @@ -53,6 +59,13 @@ export class FileSizeResolver {
return this
}

/**
* Returns the file size with the provided metric ("bytes" by default).
*/
async then (onfulfilled: (size: number) => number): Promise<number> {
return this.calculate().then(size => onfulfilled(size))
}

private async calculate (): Promise<number> {
const stats = await Fs.stat(this.filePath)

Expand Down
8 changes: 4 additions & 4 deletions src/filesystem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import Os from 'os'
import Path from 'path'
import { randomString, isDate } from './helper'
import { FileSizeResolver } from './file-size-resolver'
import { FileSizeBuilder } from './file-size-builder'
import Lockfile, { LockOptions, UnlockOptions, CheckOptions } from 'proper-lockfile'
import Fs, { Dirent, ObjectEncodingOptions, PathLike, SymlinkType, WriteFileOptions } from 'fs-extra'

Expand All @@ -25,10 +25,10 @@ export default Object.assign({}, Fs, {
*
* @param {String} path
*
* @returns {FileSizeResolver}
* @returns {FileSizeBuilder}
*/
size (path: string): FileSizeResolver {
return new FileSizeResolver(path)
size (path: string): FileSizeBuilder {
return new FileSizeBuilder(path)
},

/**
Expand Down
12 changes: 12 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,18 @@ test('isDirectory', async () => {
).toBe(false)
})

test('size (resolves to bytes when used as promise)', async () => {
const file = await ensureTempFile()
expect(
await Filesystem.size(file)
).toEqual(0)

await Filesystem.writeFile(file, 'hello')
expect(
await Filesystem.size(file)
).toEqual(5)
})

test('size in bytes', async () => {
const file = await ensureTempFile()
expect(
Expand Down

0 comments on commit 9ea6c02

Please sign in to comment.