Skip to main content

formatSize

Description

Formats the number that indicates the file size

Usage

formatSize(size: number): string;

Parameters

The function takes the size of a file in bytes and returns a string with the formatted size and units.

Example

The example below shows how to get extraInfo data and return the size of each item using the formatSize function, and display the number of items in a folder using the getSizeAndCount custom function.

<script>
import { getData, getDrive } from "../data";
import { Filemanager } from "@wx/svelte-filemanager";
import { formatSize } from "@wx/filemanager-store"; // import the helper function

function requestInfo(file) {
if (file.type === "folder") {
const { size, folders, files } = getSizeAndCount(file);

let getString = (number, name) =>
number ? `${number} ${name + (number === 1 ? "" : "s")}` : "";

const foldersStr = getString(folders, "folder");

return {
Size: formatSize(size), // format the size
Count:
(foldersStr ? `${foldersStr}, ` : "") +
getString(files, "file"),
};
}
}

function getSizeAndCount(file) {
const dimensions = {
size: 0,
folders: 0,
files: 0,
};

file.data?.forEach(item => {
dimensions.size = dimensions.size + item.size || 0;
dimensions[`${item.type}s`] = ++dimensions[`${item.type}s`];

const result = getSizeAndCount(item);
for (let key in result) {
dimensions[key] = dimensions[key] + result[key];
}
});

return dimensions;
}
</script>

<Filemanager
data={getData()}
drive={getDrive()}
panels={[{ selected: ["/Code"] }]}
preview
extraInfo={requestInfo}
/>