Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: file / directory watcher (WIP) #13

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/file-watcher/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"name": "your-project-name",
"version": "1.0.0",
"type": "module"
}
14 changes: 14 additions & 0 deletions packages/file-watcher/src/example.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// @ts-check
import { promises as fs } from 'fs'; // Assuming fs promises for async reading
import { FileWatcher } from './file-watcher.js';

(async () => {
const watcher = new FileWatcher(fs);

const { env } = process;
console.log('watching Downloads');
for await (const file of watcher.watchDirectory(`${env.HOME}/Downloads`)) {
console.log(`New file added: ${file.getName()}`);
console.log(await file.getContent()); // Call getContent to read the file
}
})();
54 changes: 54 additions & 0 deletions packages/file-watcher/src/file-watcher.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// @ts-check
import path from 'node:path';
import fs from 'node:fs/promises';
import { Far } from '@endo/far';

export class FileWatcher {
/**
* @param {Pick<typeof import('fs/promises'), 'readFile' | 'watch'>} fs
*/
constructor(fs) {
this.fs = fs;
}

/**
* @param {string} directory
* @param {Parameters<import('fs/promises').watch>[1]} options
*/
async *watchDirectory(directory, options = {}) {
const events = this.fs.watch(directory, options);

for await (const event of events) {
console.log('@@', event);
const { filename } = event;
// XXX Buffer not supported
if (typeof filename !== 'string') break;
const fullPath = path.join(directory, filename);
yield Far('File', {
getName: () => filename,
getContent: async () => {
const content = await this.fs.readFile(fullPath, 'utf-8');
return content;
},
});
}
}
}

const watcher = new FileWatcher(fs);

export const make = () => {
return Far('FileWatcherFactory', {
/** @param {string} path */
make: path =>
Far('FileWatcher', {
watch: () => {
const events = watcher.watchDirectory(path);
return Far('FileEvents', {
next: () => events.next(),
return: () => events.return(),
});
},
}),
});
};
Loading