|
| 1 | +'use strict'; |
| 2 | +const common = require('../common'); |
| 3 | + |
| 4 | +if (common.isIBMi) |
| 5 | + common.skip('IBMi does not support `fs.watch()`'); |
| 6 | + |
| 7 | +const { watch, writeFile } = require('fs/promises'); |
| 8 | +const fs = require('fs'); |
| 9 | +const assert = require('assert'); |
| 10 | +const { join } = require('path'); |
| 11 | +const { setTimeout } = require('timers/promises'); |
| 12 | +const tmpdir = require('../common/tmpdir'); |
| 13 | + |
| 14 | +class WatchTestCase { |
| 15 | + constructor(shouldInclude, dirName, files) { |
| 16 | + this.dirName = dirName; |
| 17 | + this.files = files; |
| 18 | + this.shouldSkip = !shouldInclude; |
| 19 | + } |
| 20 | + get dirPath() { return tmpdir.resolve(this.dirName); } |
| 21 | + filePath(fileName) { return join(this.dirPath, fileName); } |
| 22 | + |
| 23 | + async run() { |
| 24 | + await Promise.all([this.watchFiles(), this.writeFiles()]); |
| 25 | + assert(!this.files.length); |
| 26 | + } |
| 27 | + async watchFiles() { |
| 28 | + const watcher = watch(this.dirPath); |
| 29 | + for await (const evt of watcher) { |
| 30 | + const idx = this.files.indexOf(evt.filename); |
| 31 | + if (idx < 0) continue; |
| 32 | + this.files.splice(idx, 1); |
| 33 | + await setTimeout(common.platformTimeout(100)); |
| 34 | + if (!this.files.length) break; |
| 35 | + } |
| 36 | + } |
| 37 | + async writeFiles() { |
| 38 | + for (const fileName of [...this.files]) { |
| 39 | + await writeFile(this.filePath(fileName), Date.now() + fileName.repeat(1e4)); |
| 40 | + } |
| 41 | + await setTimeout(common.platformTimeout(100)); |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +const kCases = [ |
| 46 | + // Watch on a directory should callback with a filename on supported systems |
| 47 | + new WatchTestCase( |
| 48 | + common.isLinux || common.isMacOS || common.isWindows || common.isAIX, |
| 49 | + 'watch1', |
| 50 | + ['foo', 'bar', 'baz'] |
| 51 | + ), |
| 52 | +]; |
| 53 | + |
| 54 | +tmpdir.refresh(); |
| 55 | + |
| 56 | +for (const testCase of kCases) { |
| 57 | + if (testCase.shouldSkip) continue; |
| 58 | + fs.mkdirSync(testCase.dirPath); |
| 59 | + testCase.run().then(common.mustCall()); |
| 60 | +} |
0 commit comments