This repository has been archived by the owner on Dec 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathutils.js
82 lines (75 loc) · 1.99 KB
/
utils.js
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
74
75
76
77
78
79
80
81
82
// @ts-ignore
import Table from 'cli-table'
import fs from 'fs'
import { CID } from 'multiformats/cid'
import { sha256 } from 'multiformats/hashes/sha2'
/**
* Turns a number (representing a byte size) into a readable format.
*
* @param {number} size - The size in bytes
* @returns {string} A humanized version of the number.
*/
const kb = 1024
const mb = Math.pow(kb, 2)
const gb = Math.pow(kb, 3)
/**
* Humanize a number of bytes into a readable string.
* @param {number} size - The size in bytes.
* @returns {string} The size in a human readable string.
*/
export function humanizeBytes (size) {
if (size < kb / 2) {
return size.toFixed(2) + 'B'
} else if (size < mb / 2) {
return (size / kb / 2).toPrecision(2) + 'KB'
} else if (size < gb / 2) {
return (size / mb).toFixed(2) + 'MB'
}
return (size / gb).toFixed(2) + 'GB'
}
/**
* @param {string} pathName - The path to check if it's a directory
* @returns {boolean}
*/
export const isDirectory = (pathName) =>
fs.existsSync(pathName) && fs.lstatSync(pathName).isDirectory()
/**
* @async
* @param {Uint8Array} bytes - The bytes to get a CAR cid for.
* @returns {Promise<CID>}
*/
export async function bytesToCarCID (bytes) {
// this CID represents the byte content, but doesn't 'link' with the blocks inside
const digest = await sha256.digest(bytes)
return CID.createV1(0x202, digest)
}
/**
* @param {Array<string>} head
* @returns
*/
export function buildSimpleConsoleTable (head) {
const table = new Table({
truncate: false,
head: head || [],
chars: {
top: '',
'top-mid': '',
'top-left': '',
'top-right': '',
bottom: '',
'bottom-mid': '',
'bottom-left': '',
'bottom-right': '',
left: '',
'left-mid': '',
mid: '',
'mid-mid': '',
right: '',
'right-mid': '',
middle: ' '
},
style: { 'padding-left': 0, 'padding-right': 2, head: ['blue'] }
})
table.push(new Array(head.length).fill('--------'))
return table
}