create-file.worker.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import Worktank from 'worktank';
  2. import os from 'node:os';
  3. import process from 'node:process';
  4. import type { Span } from '../trace';
  5. import { availableParallelism } from 'foxts/available-parallelism';
  6. const pool = new Worktank({
  7. pool: {
  8. name: 'process-phishing-domains',
  9. size: (availableParallelism(os) - 1) || 1
  10. },
  11. worker: {
  12. autoAbort: 10000, // The maximum number of milliseconds to wait for the result from the worker, if exceeded the worker is terminated and the execution promise rejects
  13. autoTerminate: 30000, // The interval of milliseconds at which to check if the pool can be automatically terminated, to free up resources, workers will be spawned up again if needed
  14. env: {},
  15. methods: {
  16. // eslint-disable-next-line object-shorthand -- workertank
  17. compareAndWriteFile: async function (
  18. linesA: string[], filePath: string,
  19. importMetaUrl: string
  20. ): Promise<void> {
  21. const { default: module } = await import('node:module');
  22. const __require = module.createRequire(importMetaUrl);
  23. const fs = __require('fs') as typeof import('fs');
  24. const { readFileByLine } = __require('./fetch-text-by-line') as typeof import('./fetch-text-by-line');
  25. const { fileEqual } = __require('./create-file') as typeof import('./create-file');
  26. const path = __require('node:path') as typeof import('node:path');
  27. const { fastStringArrayJoin } = __require('foxts/fast-string-array-join') as typeof import('foxts/fast-string-array-join');
  28. const picocolors = __require('picocolors') as typeof import('picocolors');
  29. let isEqual = false;
  30. if (fs.existsSync(filePath)) {
  31. isEqual = await fileEqual(linesA, readFileByLine(filePath));
  32. } else {
  33. console.log(`${filePath} does not exists, writing...`);
  34. // isEqual = false; // isEqual is false by default anyway
  35. }
  36. if (isEqual) {
  37. console.log(picocolors.gray(picocolors.dim(`same content, bail out writing: ${filePath}`)));
  38. return;
  39. }
  40. const dir = path.dirname(filePath);
  41. if (!fs.existsSync(dir)) {
  42. fs.mkdirSync(dir, { recursive: true });
  43. }
  44. fs.writeFileSync(filePath, fastStringArrayJoin(linesA, '\n') + '\n', { encoding: 'utf-8' });
  45. }
  46. }
  47. }
  48. });
  49. export function compareAndWriteFileInWorker(span: Span, linesA: string[], filePath: string) {
  50. return span.traceChildAsync(`compare and write (worker) ${filePath}`, () => pool.exec('compareAndWriteFile', [linesA, filePath, import.meta.url]));
  51. }
  52. process.on('beforeExit', () => pool.terminate());