diff --git a/test/async-hooks/test-statwatcher.js b/test/async-hooks/test-statwatcher.js index 70b3d64ba4afe8..d24aab584029d7 100644 --- a/test/async-hooks/test-statwatcher.js +++ b/test/async-hooks/test-statwatcher.js @@ -59,10 +59,32 @@ checkInvocations(statwatcher1, { init: 1 }, 'watcher1: when started to watch second file'); checkWatcherStart('watcher2', statwatcher2); -setTimeout(() => fs.writeFileSync(file1, 'foo++'), - common.platformTimeout(100)); +let w2Initialized = false; +let writeFile2AfterW1 = false; + +const onW2Initialized = (curr, prev) => { + if (curr.nlink !== 0 || prev.nlink !== 0) + return; + + w2.removeListener('change', onW2Initialized); + w2Initialized = true; + if (writeFile2AfterW1) { + setTimeout(() => fs.writeFileSync(file2, 'bar++'), + common.platformTimeout(100)); + } +}; +w2.on('change', onW2Initialized); + w1.on('change', common.mustCallAtLeast((curr, prev) => { console.log('w1 change to', curr, 'from', prev); + // Wait for the initial ENOENT poll before creating the file. Otherwise the + // first stat can race with the write and use the created file as the baseline. + if (curr.nlink === 0 && prev.nlink === 0) { + setTimeout(() => fs.writeFileSync(file1, 'foo++'), + common.platformTimeout(100)); + return; + } + // Wait until we get the write above. if (prev.size !== 0 || curr.size !== 5) return; @@ -74,8 +96,11 @@ w1.on('change', common.mustCallAtLeast((curr, prev) => { checkInvocations(statwatcher2, { init: 1 }, 'watcher2: when unwatched first file'); - setTimeout(() => fs.writeFileSync(file2, 'bar++'), - common.platformTimeout(100)); + writeFile2AfterW1 = true; + if (w2Initialized) { + setTimeout(() => fs.writeFileSync(file2, 'bar++'), + common.platformTimeout(100)); + } w2.on('change', common.mustCallAtLeast((curr, prev) => { console.log('w2 change to', curr, 'from', prev); // Wait until we get the write above.