clients get file change notifications

This commit is contained in:
2024-11-15 07:56:53 -07:00
parent 0366b37586
commit a37071b584
9 changed files with 454 additions and 17 deletions

55
nextjs/src/websocket.js Normal file
View File

@@ -0,0 +1,55 @@
import { createServer } from "node:http";
import next from "next";
import { Server } from "socket.io";
import chokidar from "chokidar";
import path from "path";
const dev = process.env.NODE_ENV !== "production";
const hostname = "localhost";
const port = 3000;
// when using middleware `hostname` and `port` must be provided below
const app = next({ dev, hostname, port });
const handler = app.getRequestHandler();
const folderToWatch = path.join(process.cwd(), "./storage");
console.log("watching folder", folderToWatch);
app.prepare().then(() => {
const httpServer = createServer(handler);
const io = new Server(httpServer);
const watcher = chokidar.watch(folderToWatch, { persistent: true });
io.on("connection", (socket) => {
console.log("websocket connection created");
// Define a change event handler
const changeHandler = (filePath) => {
const relativePath = filePath.replace(folderToWatch, "")
console.log(`Sending file changed websocket message: ${relativePath}`);
socket.emit("fileChanged", `File changed: ${filePath}`);
};
// Attach the change event handler
watcher.on("change", changeHandler);
// Clean up the change event handler when the client disconnects
socket.on("disconnect", () => {
console.log("Client disconnected");
watcher.off("change", changeHandler); // Remove the event listener
});
});
httpServer
.once("error", (err) => {
console.error(err);
process.exit(1);
})
.listen(port, () => {
console.log(`> Ready on http://${hostname}:${port}`);
});
});