create-file.worker.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import Worktank from 'worktank';
  2. import os from 'node:os';
  3. import process from 'node:process';
  4. import type { Span } from '../trace';
  5. const pool = new Worktank({
  6. name: 'process-phishing-domains',
  7. size: Math.max(2, Math.max(1, ('availableParallelism' in os ? os.availableParallelism() : (os as typeof import('node:os')).cpus().length) - 1)),
  8. timeout: 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
  9. warmup: true,
  10. 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
  11. env: {},
  12. methods: {
  13. // eslint-disable-next-line object-shorthand -- workertank
  14. compareAndWriteFile: async function (
  15. linesA: string[], filePath: string,
  16. importMetaUrl: string
  17. ): Promise<void> {
  18. const { default: module } = await import('node:module');
  19. const __require = module.createRequire(importMetaUrl);
  20. const fs = __require('fs') as typeof import('fs');
  21. const { readFileByLine } = __require('./fetch-text-by-line') as typeof import('./fetch-text-by-line');
  22. const { fileEqual } = __require('./create-file') as typeof import('./create-file');
  23. const path = __require('node:path') as typeof import('node:path');
  24. const { fastStringArrayJoin } = __require('foxts/fast-string-array-join') as typeof import('foxts/fast-string-array-join');
  25. const picocolors = __require('picocolors') as typeof import('picocolors');
  26. let isEqual = false;
  27. if (fs.existsSync(filePath)) {
  28. isEqual = await fileEqual(linesA, readFileByLine(filePath));
  29. } else {
  30. console.log(`${filePath} does not exists, writing...`);
  31. // isEqual = false; // isEqual is false by default anyway
  32. }
  33. if (isEqual) {
  34. console.log(picocolors.gray(picocolors.dim(`same content, bail out writing: ${filePath}`)));
  35. return;
  36. }
  37. const dir = path.dirname(filePath);
  38. if (!fs.existsSync(dir)) {
  39. fs.mkdirSync(dir, { recursive: true });
  40. }
  41. fs.writeFileSync(filePath, fastStringArrayJoin(linesA, '\n') + '\n', { encoding: 'utf-8' });
  42. }
  43. }
  44. });
  45. export function compareAndWriteFileInWorker(span: Span, linesA: string[], filePath: string) {
  46. return span.traceChildAsync(`compare and write ${filePath}`, () => pool.exec('compareAndWriteFile', [linesA, filePath, import.meta.url]));
  47. }
  48. process.on('beforeExit', () => pool.terminate());