Skip to content

Commit 45e8f37

Browse files
committed
fs: add recursive watch to linux
1 parent fdadea8 commit 45e8f37

File tree

5 files changed

+220
-19
lines changed

5 files changed

+220
-19
lines changed

doc/api/fs.md

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4377,10 +4377,6 @@ the returned {fs.FSWatcher}.
43774377
The `fs.watch` API is not 100% consistent across platforms, and is
43784378
unavailable in some situations.
43794379
4380-
The recursive option is only supported on macOS and Windows.
4381-
An `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` exception will be thrown
4382-
when the option is used on a platform that does not support it.
4383-
43844380
On Windows, no events will be emitted if the watched directory is moved or
43854381
renamed. An `EPERM` error is reported when the watched directory is deleted.
43864382

lib/fs.js

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ const {
5757

5858
const pathModule = require('path');
5959
const { isArrayBufferView } = require('internal/util/types');
60+
const linuxWatcher = require('internal/fs/linux_watcher');
6061

6162
// We need to get the statValues from the binding at the callsite since
6263
// it's re-initialized after deserialization.
@@ -68,7 +69,6 @@ const {
6869
codes: {
6970
ERR_FS_FILE_TOO_LARGE,
7071
ERR_INVALID_ARG_VALUE,
71-
ERR_FEATURE_UNAVAILABLE_ON_PLATFORM,
7272
},
7373
AbortError,
7474
uvErrmapGet,
@@ -161,7 +161,7 @@ let FileReadStream;
161161
let FileWriteStream;
162162

163163
const isWindows = process.platform === 'win32';
164-
const isOSX = process.platform === 'darwin';
164+
const isLinux = process.platform === 'linux';
165165

166166

167167
function showTruncateDeprecation() {
@@ -2297,13 +2297,22 @@ function watch(filename, options, listener) {
22972297

22982298
if (options.persistent === undefined) options.persistent = true;
22992299
if (options.recursive === undefined) options.recursive = false;
2300-
if (options.recursive && !(isOSX || isWindows))
2301-
throw new ERR_FEATURE_UNAVAILABLE_ON_PLATFORM('watch recursively');
2302-
const watcher = new watchers.FSWatcher();
2303-
watcher[watchers.kFSWatchStart](filename,
2304-
options.persistent,
2305-
options.recursive,
2306-
options.encoding);
2300+
2301+
let watcher;
2302+
2303+
// TODO(anonrig): Remove this when/if libuv supports it.
2304+
// libuv does not support recursive file watch on Linux due to
2305+
// the limitations of inotify.
2306+
if (options.recursive && isLinux) {
2307+
watcher = new linuxWatcher.FSWatcher(options);
2308+
watcher[linuxWatcher.kFSWatchStart](filename);
2309+
} else {
2310+
watcher = new watchers.FSWatcher();
2311+
watcher[watchers.kFSWatchStart](filename,
2312+
options.persistent,
2313+
options.recursive,
2314+
options.encoding);
2315+
}
23072316

23082317
if (listener) {
23092318
watcher.addListener('change', listener);

lib/internal/fs/linux_watcher.js

Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
'use strict';
2+
3+
const { EventEmitter } = require('events');
4+
const path = require('path');
5+
const { SafeMap, Symbol, ObjectKeys } = primordials;
6+
const { validateObject } = require('internal/validators');
7+
8+
const kFSWatchStart = Symbol('kFSWatchStart');
9+
10+
let internalSync;
11+
let internalPromises;
12+
13+
function lazyLoadFsPromises() {
14+
internalPromises ??= require('fs/promises');
15+
return internalPromises;
16+
}
17+
18+
function lazyLoadFsSync() {
19+
internalSync ??= require('fs');
20+
return internalSync;
21+
}
22+
23+
async function traverse(dir, files = new SafeMap()) {
24+
const { stat, opendir } = lazyLoadFsPromises();
25+
26+
files.set(dir, await stat(dir));
27+
28+
try {
29+
const directory = await opendir(dir);
30+
31+
for await (const file of directory) {
32+
const f = path.join(dir, file);
33+
34+
try {
35+
const stats = await stat(f);
36+
37+
files.set(f, stats);
38+
39+
if (stats.isDirectory()) {
40+
await traverse(f, files);
41+
}
42+
} catch (error) {
43+
if (error.code !== 'ENOENT' || error.code !== 'EPERM') {
44+
throw error;
45+
}
46+
}
47+
48+
}
49+
} catch (error) {
50+
if (error.code !== 'EACCES') {
51+
throw error;
52+
}
53+
}
54+
55+
return files;
56+
}
57+
58+
class FSWatcher extends EventEmitter {
59+
#options = null;
60+
#closed = false;
61+
#files = new SafeMap();
62+
63+
/**
64+
* @param {{
65+
* persistent?: boolean;
66+
* recursive?: boolean;
67+
* encoding?: string;
68+
* signal?: AbortSignal;
69+
* }} [options]
70+
*/
71+
constructor(options) {
72+
super();
73+
74+
validateObject(options, 'options');
75+
this.#options = options;
76+
}
77+
78+
async close() {
79+
const { unwatchFile } = lazyLoadFsPromises();
80+
this.#closed = true;
81+
82+
for (const file of ObjectKeys(this.#files)) {
83+
await unwatchFile(file);
84+
}
85+
86+
this.emit('close');
87+
}
88+
89+
/**
90+
* @param {string} file
91+
*/
92+
#watchFile(file) {
93+
const { opendir } = lazyLoadFsPromises();
94+
const { stat, watchFile } = lazyLoadFsSync();
95+
96+
watchFile(file, this.#options, (event, payload) => {
97+
const existingStat = this.#files.get(file);
98+
99+
if (existingStat && !existingStat.isDirectory() &&
100+
event.nlink !== 0 && existingStat.mtime.getTime() === event.mtime.getTime()) {
101+
return;
102+
}
103+
104+
this.#files.set(file, event);
105+
106+
if (!event.isDirectory()) {
107+
this.emit(event, payload);
108+
} else {
109+
opendir(file)
110+
.then(async (files) => {
111+
for await (const subfile of files) {
112+
const f = path.join(file, subfile);
113+
114+
if (!this.#files.has(f)) {
115+
stat(f, (error, stat) => {
116+
if (error) {
117+
return;
118+
}
119+
120+
this.#files.set(f, stat);
121+
this.#watchFile(f);
122+
});
123+
}
124+
}
125+
});
126+
}
127+
});
128+
}
129+
130+
/**
131+
* @param {string | Buffer | URL} filename
132+
*/
133+
async [kFSWatchStart](filename) {
134+
this.#closed = false;
135+
this.#files = await traverse(filename);
136+
137+
this.#watchFile(filename);
138+
139+
for (const f in this.#files) {
140+
this.#watchFile(f);
141+
}
142+
}
143+
}
144+
145+
module.exports = {
146+
FSWatcher,
147+
kFSWatchStart,
148+
};
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
5+
// Only run these tests on Linux.
6+
// TODO: Uncomment this
7+
// if (!common.isLinux) {
8+
// return;
9+
// }
10+
11+
const assert = require('assert');
12+
const path = require('path');
13+
const fs = require('fs');
14+
15+
const tmpdir = require('../common/tmpdir');
16+
17+
const testDir = tmpdir.path;
18+
const filenameOne = 'watch.txt';
19+
20+
tmpdir.refresh();
21+
22+
const testsubdir = fs.mkdtempSync(testDir + path.sep);
23+
const relativePathOne = path.join(path.basename(testsubdir), filenameOne);
24+
const filepathOne = path.join(testsubdir, filenameOne);
25+
26+
const watcher = fs.watch(testDir, { recursive: true });
27+
28+
let watcherClosed = false;
29+
watcher.on('change', function(event, filename) {
30+
assert.ok(event === 'change' || event === 'rename');
31+
32+
// Ignore stale events generated by mkdir and other tests
33+
if (filename !== relativePathOne)
34+
return;
35+
36+
if (common.isOSX) {
37+
clearInterval(interval);
38+
}
39+
watcher.close();
40+
watcherClosed = true;
41+
});
42+
43+
let interval;
44+
if (common.isOSX) {
45+
interval = setInterval(function() {
46+
fs.writeFileSync(filepathOne, 'world');
47+
}, 10);
48+
} else {
49+
fs.writeFileSync(filepathOne, 'world');
50+
}
51+
52+
process.on('exit', function() {
53+
assert(watcherClosed, 'watcher Object was not closed');
54+
});

test/parallel/test-fs-watch-recursive.js

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,6 @@ tmpdir.refresh();
1717
const testsubdir = fs.mkdtempSync(testDir + path.sep);
1818
const relativePathOne = path.join(path.basename(testsubdir), filenameOne);
1919
const filepathOne = path.join(testsubdir, filenameOne);
20-
21-
if (!common.isOSX && !common.isWindows) {
22-
assert.throws(() => { fs.watch(testDir, { recursive: true }); },
23-
{ code: 'ERR_FEATURE_UNAVAILABLE_ON_PLATFORM' });
24-
return;
25-
}
2620
const watcher = fs.watch(testDir, { recursive: true });
2721

2822
let watcherClosed = false;

0 commit comments

Comments
 (0)