|
| 1 | +// Flags: --expose-internals |
| 2 | +import * as common from '../common/index.mjs'; |
| 3 | +import tmpdir from '../common/tmpdir.js'; |
| 4 | +import assert from 'node:assert'; |
| 5 | +import { writeFileSync } from 'node:fs'; |
| 6 | +import { createRequire } from 'node:module'; |
| 7 | + |
| 8 | +if (common.isIBMi) |
| 9 | + common.skip('IBMi does not support `fs.watch()`'); |
| 10 | + |
| 11 | +const require = createRequire(import.meta.url); |
| 12 | +const timers = require('node:timers'); |
| 13 | +const originalSetTimeout = timers.setTimeout; |
| 14 | +const originalClearTimeout = timers.clearTimeout; |
| 15 | +const { promise, resolve } = Promise.withResolvers(); |
| 16 | +const debounce = 1000; |
| 17 | +let debounceTimer; |
| 18 | +let debounceTimerCallback; |
| 19 | +let debounceTimerCleared = false; |
| 20 | + |
| 21 | +timers.setTimeout = function(fn, delay, ...args) { |
| 22 | + // Only intercept the FilesWatcher debounce timer configured below. |
| 23 | + if (delay === debounce) { |
| 24 | + const timer = { |
| 25 | + __proto__: null, |
| 26 | + ref() { return this; }, |
| 27 | + unref() { return this; }, |
| 28 | + }; |
| 29 | + debounceTimer = timer; |
| 30 | + debounceTimerCallback = () => { |
| 31 | + if (!debounceTimerCleared) { |
| 32 | + fn(...args); |
| 33 | + } |
| 34 | + }; |
| 35 | + resolve(); |
| 36 | + return timer; |
| 37 | + } |
| 38 | + return originalSetTimeout(fn, delay, ...args); |
| 39 | +}; |
| 40 | + |
| 41 | +timers.clearTimeout = function(timer) { |
| 42 | + if (timer === debounceTimer) { |
| 43 | + debounceTimerCleared = true; |
| 44 | + } |
| 45 | + return originalClearTimeout(timer); |
| 46 | +}; |
| 47 | + |
| 48 | +try { |
| 49 | + const { FilesWatcher } = require('internal/watch_mode/files_watcher'); |
| 50 | + |
| 51 | + tmpdir.refresh(); |
| 52 | + const file = tmpdir.resolve('watcher-clear.js'); |
| 53 | + writeFileSync(file, '0'); |
| 54 | + |
| 55 | + const watcher = new FilesWatcher({ debounce, mode: 'all' }); |
| 56 | + watcher.on('changed', common.mustNotCall()); |
| 57 | + watcher.watchPath(file, false); |
| 58 | + |
| 59 | + const interval = setInterval(() => writeFileSync(file, `${Date.now()}`), 50); |
| 60 | + await promise; |
| 61 | + clearInterval(interval); |
| 62 | + |
| 63 | + watcher.clear(); |
| 64 | + assert.strictEqual(debounceTimerCleared, true); |
| 65 | + debounceTimerCallback(); |
| 66 | +} finally { |
| 67 | + timers.setTimeout = originalSetTimeout; |
| 68 | + timers.clearTimeout = originalClearTimeout; |
| 69 | +} |
0 commit comments