Skip to content

Commit

Permalink
fix: correctly output filename when watching files (#907)
Browse files Browse the repository at this point in the history
  • Loading branch information
G-Rath committed Jun 2, 2023
1 parent 9173db4 commit fbde74f
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
36 changes: 36 additions & 0 deletions src/__tests__/volume.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1090,6 +1090,42 @@ describe('volume', () => {
});
});
describe('.watch(path[, options], listener)', () => {
it('should handle watching a file correctly', () => {
const vol = Volume.fromJSON({ '/tmp/foo.js': 'hello test' });
vol.writeFileSync('/tmp/foo.js', 'hello test');

const mockCallback = jest.fn();
const writtenContent = 'hello world';
const watcher = vol.watch('/tmp/foo.js', mockCallback as any);

try {
vol.writeFileSync('/tmp/foo.js', writtenContent);

expect(mockCallback).toBeCalledTimes(2);
expect(mockCallback).toBeCalledWith('change', 'foo.js');
} finally {
watcher.close();
}
});

it('should handle watching a directory correctly', () => {
const vol = Volume.fromJSON({ '/tmp/foo.js': 'hello test' });
vol.mkdirSync('/tmp/foo-dir');

const mockCallback = jest.fn();
const writtenContent = 'hello world';
const watcher = vol.watch('/tmp/foo-dir', mockCallback as any);

try {
vol.writeFileSync('/tmp/foo-dir/foo.js', writtenContent);

expect(mockCallback).toBeCalledTimes(1);
expect(mockCallback).toBeCalledWith('rename', 'foo.js');
} finally {
watcher.close();
}
});

it('Calls listener on .watch when renaming with recursive=true', done => {
const vol = new Volume();
vol.mkdirSync('/test');
Expand Down
10 changes: 9 additions & 1 deletion src/volume.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2759,7 +2759,15 @@ export class FSWatcher extends EventEmitter {
const watchLinkNodeChanged = (link: Link) => {
const filepath = link.getPath();
const node = link.getNode();
const onNodeChange = () => this.emit('change', 'change', relative(this._filename, filepath));
const onNodeChange = () => {
let filename = relative(this._filename, filepath);

if (!filename) {
filename = this._getName();
}

return this.emit('change', 'change', filename);
};
node.on('change', onNodeChange);

const removers = this._listenerRemovers.get(node.ino) ?? [];
Expand Down

0 comments on commit fbde74f

Please sign in to comment.