Skip to content

Commit

Permalink
fs: fixes recursive fs.watch crash on Linux when deleting files
Browse files Browse the repository at this point in the history
Signed-off-by: Matteo Collina <[email protected]>
Fixes: nodejs#52018
  • Loading branch information
mcollina committed Apr 3, 2024
1 parent a3b1fc3 commit 63d7713
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
10 changes: 7 additions & 3 deletions lib/internal/fs/recursive_watch.js
Original file line number Diff line number Diff line change
Expand Up @@ -157,11 +157,15 @@ class FSWatcher extends EventEmitter {
persistent: this.#options.persistent,
}, (eventType, filename) => {
const existingStat = this.#files.get(file);
const currentStats = statSync(file);
let currentStats

this.#files.set(file, currentStats);
try {
currentStats = statSync(file);
this.#files.set(file, currentStats);
} catch {
}

if (currentStats.birthtimeMs === 0 && existingStat.birthtimeMs !== 0) {
if (currentStats === undefined || currentStats.birthtimeMs === 0 && existingStat.birthtimeMs !== 0) {
// The file is now deleted
this.#files.delete(file);
this.#watchers.delete(file);
Expand Down
25 changes: 25 additions & 0 deletions test/parallel/test-fs-watch-recursive-delete.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
'use strict'

const common = require('../common')
const tmpdir = require('../common/tmpdir');
const fs = require('fs')
const { join } = require('path')
const assert = require('node:assert')

tmpdir.refresh();

try {
fs.mkdirSync(tmpdir.resolve('./parent/child'), { recursive: true })
} catch (e) {
console.error(e)
}

fs.writeFileSync(tmpdir.resolve('./parent/child/test.tmp'), 'test')

const watcher = fs.watch(tmpdir.resolve('./parent'), { recursive: true }, common.mustCall((eventType, filename) => {
// We are only checking for the filename to avoid having Windows, Linux and Mac specific assertions
assert.strictEqual(filename.indexOf('test.tmp') >= 0, true)
watcher.close()
}))

fs.rmSync(tmpdir.resolve('./parent/child/test.tmp'))

0 comments on commit 63d7713

Please sign in to comment.