MCPcopy Index your code
hub / github.com/nodejs/node / #watchFile

Method #watchFile

lib/internal/fs/recursive_watch.js:169–220  ·  view source on GitHub ↗
(file)

Source from the content-addressed store, hash-verified

167 }
168
169 #watchFile(file) {
170 if (this.#closed) {
171 return;
172 }
173
174 const { watch, statSync } = lazyLoadFsSync();
175
176 if (this.#files.has(file)) {
177 return;
178 }
179
180 {
181 const existingStat = statSync(file);
182 this.#files.set(file, existingStat);
183 }
184
185 const watcher = watch(file, {
186 persistent: this.#options.persistent,
187 }, (eventType, filename) => {
188 const existingStat = this.#files.get(file);
189 let currentStats;
190
191 try {
192 currentStats = statSync(file);
193 this.#files.set(file, currentStats);
194 } catch {
195 // This happens if the file was removed
196 }
197
198 if (currentStats === undefined || (currentStats.birthtimeMs === 0 && existingStat.birthtimeMs !== 0)) {
199 // The file is now deleted
200 this.#files.delete(file);
201 this.#watchers.delete(file);
202 watcher.close();
203 this.emit('change', 'rename', pathRelative(this.#rootPath, file));
204 this.#unwatchFiles(file);
205 } else if (file === this.#rootPath && this.#watchingFile) {
206 // This case will only be triggered when watching a file with fs.watch
207 this.emit('change', 'change', pathBasename(file));
208 } else if (this.#symbolicFiles.has(file)) {
209 // Stats from watchFile does not return correct value for currentStats.isSymbolicLink()
210 // Since it is only valid when using fs.lstat(). Therefore, check the existing symbolic files.
211 this.emit('change', 'rename', pathRelative(this.#rootPath, file));
212 } else if (currentStats.isDirectory()) {
213 this.#watchFolder(file);
214 } else {
215 // Watching a directory will trigger a change event for child files)
216 this.emit('change', 'change', pathRelative(this.#rootPath, file));
217 }
218 });
219 this.#watchers.set(file, watcher);
220 }
221
222 [kFSWatchStart](filename) {
223 filename = pathResolve(getValidatedPath(filename));

Callers 2

#watchFolderMethod · 0.95
[kFSWatchStart]Method · 0.95

Calls 12

#unwatchFilesMethod · 0.95
#watchFolderMethod · 0.95
lazyLoadFsSyncFunction · 0.85
watchFunction · 0.70
hasMethod · 0.65
getMethod · 0.65
deleteMethod · 0.65
closeMethod · 0.65
statSyncFunction · 0.50
setMethod · 0.45
emitMethod · 0.45
isDirectoryMethod · 0.45

Tested by

no test coverage detected