* @param {Object} options * @param {string[]} options.files * @param {(files: string[]) => void | Promise } options.onChange
(options)
| 10 | * @param {(files: string[]) => void | Promise<void>} options.onChange |
| 11 | */ |
| 12 | function watch(options) { |
| 13 | const queue = new Set(); |
| 14 | let timeoutId = null; |
| 15 | |
| 16 | function onChange(path) { |
| 17 | queue.add(path); |
| 18 | |
| 19 | if (timeoutId !== null) { |
| 20 | return; |
| 21 | } |
| 22 | |
| 23 | timeoutId = setTimeout(async () => { |
| 24 | timeoutId = null; |
| 25 | try { |
| 26 | const changedFiles = Array.from(queue).sort(); |
| 27 | log.ok(`Files changed:${changedFiles.map((path) => `\n${path}`)}`); |
| 28 | queue.clear(); |
| 29 | await options.onChange(changedFiles); |
| 30 | } catch (err) { |
| 31 | log.error(err); |
| 32 | } |
| 33 | }, DEBOUNCE); |
| 34 | } |
| 35 | |
| 36 | const watcher = chokidarWatch(options.files, {ignoreInitial: true}) |
| 37 | .on('add', onChange) |
| 38 | .on('change', onChange) |
| 39 | .on('unlink', onChange); |
| 40 | |
| 41 | function stop() { |
| 42 | watcher.close(); |
| 43 | } |
| 44 | |
| 45 | process.on('exit', stop); |
| 46 | process.on('SIGINT', stop); |
| 47 | |
| 48 | return watcher; |
| 49 | } |
| 50 | |
| 51 | export default watch; |