misc.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { dirname } from 'node:path';
  2. import fs from 'node:fs';
  3. import type { PathLike } from 'node:fs';
  4. import fsp from 'node:fs/promises';
  5. export function fastStringCompare(a: string, b: string) {
  6. const lenA = a.length;
  7. const lenB = b.length;
  8. const minLen = lenA < lenB ? lenA : lenB;
  9. for (let i = 0; i < minLen; ++i) {
  10. const ca = a.charCodeAt(i);
  11. const cb = b.charCodeAt(i);
  12. if (ca > cb) return 1;
  13. if (ca < cb) return -1;
  14. }
  15. if (lenA === lenB) {
  16. return 0;
  17. }
  18. return lenA > lenB ? 1 : -1;
  19. };
  20. interface Write {
  21. (
  22. destination: string,
  23. input: NodeJS.TypedArray | string,
  24. ): Promise<unknown>
  25. }
  26. export function mkdirp(dir: string) {
  27. if (fs.existsSync(dir)) {
  28. return;
  29. }
  30. return fsp.mkdir(dir, { recursive: true });
  31. }
  32. export const writeFile: Write = async (destination: string, input, dir = dirname(destination)) => {
  33. const p = mkdirp(dir);
  34. if (p) {
  35. await p;
  36. }
  37. return fsp.writeFile(destination, input, { encoding: 'utf-8' });
  38. };
  39. export const removeFiles = async (files: string[]) => Promise.all(files.map((file) => fsp.rm(file, { force: true })));
  40. export function withBannerArray(title: string, description: string[] | readonly string[], date: Date, content: string[]) {
  41. return [
  42. '#########################################',
  43. `# ${title}`,
  44. `# Last Updated: ${date.toISOString()}`,
  45. `# Size: ${content.length}`,
  46. ...description.map(line => (line ? `# ${line}` : '#')),
  47. '#########################################',
  48. ...content,
  49. '################## EOF ##################'
  50. ];
  51. };
  52. export function isDirectoryEmptySync(path: PathLike) {
  53. const directoryHandle = fs.opendirSync(path);
  54. try {
  55. return directoryHandle.readSync() === null;
  56. } finally {
  57. directoryHandle.closeSync();
  58. }
  59. }