utils.ts 999 B

12345678910111213141516171819202122232425262728293031323334
  1. import { readdir, stat } from "node:fs";
  2. import { sum, formatBytes } from "@pureadmin/utils";
  3. const fileListTotal: number[] = [];
  4. /**
  5. * @description 获取指定文件夹中所有文件的总大小
  6. */
  7. export const getPackageSize = options => {
  8. const { folder = "dist", callback, format = true } = options;
  9. readdir(folder, (err, files: string[]) => {
  10. if (err) throw err;
  11. let count = 0;
  12. const checkEnd = () => {
  13. ++count == files.length &&
  14. callback(format ? formatBytes(sum(fileListTotal)) : sum(fileListTotal));
  15. };
  16. files.forEach((item: string) => {
  17. stat(`${folder}/${item}`, async (err, stats) => {
  18. if (err) throw err;
  19. if (stats.isFile()) {
  20. fileListTotal.push(stats.size);
  21. checkEnd();
  22. } else if (stats.isDirectory()) {
  23. getPackageSize({
  24. folder: `${folder}/${item}/`,
  25. callback: checkEnd
  26. });
  27. }
  28. });
  29. });
  30. files.length === 0 && callback(0);
  31. });
  32. };