create-file.worker.ts 2.5 KB

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