This commit is contained in:
Mark Nadal 2021-08-25 21:27:29 -07:00
commit 5df08f91cb

View File

@ -8,10 +8,16 @@ let chokidar;
try { chokidar = require('chokidar') } catch (error) { try { chokidar = require('chokidar') } catch (error) {
} // Must install chokidar to use this feature. } // Must install chokidar to use this feature.
function watch(what, opt) { /**
opt = opt || { } * Watches a directory and send all its content in the database
* @constructor
* @param {string} what - Which directory hub should watch.
* @param {Object} options - https://gun.eco/docs/hub.js#options
*/
function watch(what, options) {
options = options || { msg: true }
let modifiedPath = (opt.file || ""); let modifiedPath = (options.file || "");
let watcher; let watcher;
try { try {
@ -26,31 +32,33 @@ function watch(what, opt) {
// Handle events ! // Handle events !
watcher watcher
.on('add', async function(path) { .on('add', async function(path) {
if (options.msg) log(`File ${path} has been added`);
log(`File ${path} has been added`); gun.get('hub').get(modifiedPath + '/' + path).put(fs.readFileSync(path, 'utf-8'))
gun.get('hub').get(modifiedPath + '/' + path).put(fs.readFileSync(path, 'utf-8').replace(/\n/gm, ""))
}) })
.on('change', async function(path) { .on('change', async function(path) {
log(`File ${path} has been changed`); if (options.msg) log(`File ${path} has been changed`);
gun.get('hub').get(modifiedPath + '/' + path).put(fs.readFileSync(path, 'utf-8').replace(/\n/gm, "")) gun.get('hub').get(modifiedPath + '/' + path).put(fs.readFileSync(path, 'utf-8'))
}) })
.on('unlink', async function (path) { .on('unlink', async function (path) {
log(`File ${path} has been removed`); if(options.msg) log(`File ${path} has been removed`);
gun.get('hub').get(modifiedPath + '/' + path).put(null) gun.get('hub').get(modifiedPath + '/' + path).put(null)
}) })
.on('addDir', path => log(`Directory ${path} has been added`)) if (options.msg) {
.on('unlinkDir', path => log(`Directory ${path} has been removed`)) watcher
.on('error', error => log(`Watcher error: ${error}`)) .on('addDir', path => log(`Directory ${path} has been added`))
.on('ready', () => log('Initial scan complete. Ready for changes')) .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'))
}
} catch (err) { } catch (err) {
console.log('If you want to use the hub feature, you must install `chokidar` by typing `npm i chokidar` in your terminal.') console.log('If you want to use the hub feature, you must install `chokidar` by typing `npm i chokidar` in your terminal.')
} }
} }
module.exports = { watch : watch } module.exports = { watch : watch }