* Watches for the changes on `filename`. * @param {string | Buffer | URL} filename * @param {string | { * persistent?: boolean; * recursive?: boolean; * encoding?: string; * signal?: AbortSignal; * throwIfNoEntry?: boolean; * }} [options] * @param {( * eventType?: string, *
(filename, options, listener)
| 3030 | * @returns {watchers.FSWatcher} |
| 3031 | */ |
| 3032 | function watch(filename, options, listener) { |
| 3033 | const h = vfsState.handlers; |
| 3034 | if (h !== null) { |
| 3035 | const result = h.watch(filename, options, listener); |
| 3036 | if (result !== undefined) return result; |
| 3037 | } |
| 3038 | if (typeof options === 'function') { |
| 3039 | listener = options; |
| 3040 | } |
| 3041 | options = getOptions(options); |
| 3042 | |
| 3043 | // Don't make changes directly on options object |
| 3044 | options = copyObject(options); |
| 3045 | |
| 3046 | if (options.persistent === undefined) options.persistent = true; |
| 3047 | if (options.recursive === undefined) options.recursive = false; |
| 3048 | if (options.throwIfNoEntry === undefined) options.throwIfNoEntry = true; |
| 3049 | |
| 3050 | let watcher; |
| 3051 | const watchers = require('internal/fs/watchers'); |
| 3052 | const path = getValidatedPath(filename); |
| 3053 | // TODO(anonrig): Remove non-native watcher when/if libuv supports recursive. |
| 3054 | // As of November 2022, libuv does not support recursive file watch on all platforms, |
| 3055 | // e.g. Linux due to the limitations of inotify. |
| 3056 | if (options.recursive && !isMacOS && !isWindows) { |
| 3057 | const nonNativeWatcher = require('internal/fs/recursive_watch'); |
| 3058 | watcher = new nonNativeWatcher.FSWatcher(options); |
| 3059 | watcher[watchers.kFSWatchStart](path); |
| 3060 | } else { |
| 3061 | watcher = new watchers.FSWatcher(); |
| 3062 | watcher[watchers.kFSWatchStart](path, |
| 3063 | options.persistent, |
| 3064 | options.recursive, |
| 3065 | options.encoding, |
| 3066 | options.ignore, |
| 3067 | options.throwIfNoEntry); |
| 3068 | } |
| 3069 | |
| 3070 | if (listener) { |
| 3071 | watcher.addListener('change', listener); |
| 3072 | } |
| 3073 | if (options.signal) { |
| 3074 | if (options.signal.aborted) { |
| 3075 | process.nextTick(() => watcher.close()); |
| 3076 | } else { |
| 3077 | const listener = () => watcher.close(); |
| 3078 | kResistStopPropagation ??= require('internal/event_target').kResistStopPropagation; |
| 3079 | options.signal.addEventListener('abort', listener, { __proto__: null, [kResistStopPropagation]: true }); |
| 3080 | watcher.once('close', () => { |
| 3081 | options.signal.removeEventListener('abort', listener); |
| 3082 | }); |
| 3083 | } |
| 3084 | } |
| 3085 | |
| 3086 | return watcher; |
| 3087 | } |
| 3088 | |
| 3089 |
searching dependent graphs…