From 5ba2d9b44ff7a5fdcbca8a35cef23471910212df Mon Sep 17 00:00:00 2001 From: Hector <46224745+noctisatrae@users.noreply.github.com> Date: Tue, 3 Aug 2021 22:05:51 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=93=A6=20Adding=20the=20new=20hub=20featu?= =?UTF-8?q?re=20!=20(#1099)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Hector --- lib/hub.js | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 64 insertions(+), 4 deletions(-) diff --git a/lib/hub.js b/lib/hub.js index 38db6ee1..d3903791 100644 --- a/lib/hub.js +++ b/lib/hub.js @@ -1,5 +1,65 @@ -var fs = require('fs'); +const fs = require('fs'); +const Gun = require('../index.js'); -fs.watch('.', {persistent: false, recursive: true}, function(eve, name){ - console.log("changed!", eve, name); -}) \ No newline at end of file +const gun = Gun(); + +let chokidar; + +try { chokidar = require('chokidar') } catch { + console.log('Type "npm i chokidar" if you want to use the hub feature !') +} + +function watch(what, timeout) { + timeout = timeout || 2000 + + // Set up the file watcher ! + const watcher = chokidar.watch(what, { + ignored: /(^|[\/\\])\../, // ignore dotfiles + persistent: true + }); + + const log = console.log.bind(console); + + // Handle events ! + + watcher + .on('add', async function(path) { + + log(`File ${path} has been added`); + + let container = gun.get(path).put({ + file: path, + content: fs.readFileSync(path, 'utf8') + }) + gun.get('hub').set(container).then(console.log('Done!')); + + }) + .on('change', async function(path) { + + log(`File ${path} has been changed`); + + let container = gun.get(path).put({ + file: path, + content: fs.readFileSync(path, 'utf8') + }).then(console.log('Done!')) + + }) + .on('unlink', async function (path) { + + log(`File ${path} has been removed`); + + let container = gun.get(path).put({ + file: null, + content: null, + + }) + + }) + .on('addDir', path => log(`Directory ${path} has been added`)) + .on('unlinkDir', path => log(`Directory ${path} has been removed`)) + .on('error', error => log(`Watcher error: ${error}`)) + .on('ready', () => log('Initial scan complete. Ready for changes')) + +} + +module.exports = { watch : watch, } \ No newline at end of file