UNPKG

simple-autoreload-server

Version:

Simple Web Server with live/autoreload features without browser extensions.

100 lines (98 loc) 3.4 kB
/* * simple-autoreload-server v0.2.15 - 2021-05-22 * <https://github.com/cytb/simple-autoreload-server> * * Copyright (c) 2021 cytb * * Licensed under the MIT License. */ (function(){ var fs, path, RecursiveWatcher, out$ = typeof exports != 'undefined' && exports || this; fs = require('fs'); path = require('path'); RecursiveWatcher = (function(){ RecursiveWatcher.displayName = 'RecursiveWatcher'; var prototype = RecursiveWatcher.prototype, constructor = RecursiveWatcher; function RecursiveWatcher(arg$){ var ref$; this.path = arg$.path, this.delay = (ref$ = arg$.delay) != null ? ref$ : 30, this.update = (ref$ = arg$.update) != null ? ref$ : function(){}, this.error = (ref$ = arg$.error) != null ? ref$ : function(){}, this.recursive = (ref$ = arg$.recursive) != null ? ref$ : false, this.followSymlinks = (ref$ = arg$.followSymlinks) != null ? ref$ : false; this.watchers = []; } prototype.findDir = function(root){ var dirs, queue, dir, i$, ref$, len$, file, fullPath, node, ex; dirs = []; queue = [root]; while (dir = queue.shift()) { try { dirs.push(dir); for (i$ = 0, len$ = (ref$ = fs.readdirSync(dir)).length; i$ < len$; ++i$) { file = ref$[i$]; try { fullPath = path.join(dir, file); node = fs.lstatSync(fullPath); if (!node.isDirectory() || (node.isSymbolicLink() && !this.followSymlinks)) { continue; } queue.push(fullPath); } catch (e$) { ex = e$; this.error(ex); } } } catch (e$) { ex = e$; this.error(ex); } } return dirs; }; prototype.start = function(arg$){ var ref$, ref1$, sessions, dirs, this$ = this; ref$ = arg$ != null ? arg$ : {}, this.update = (ref1$ = ref$.update) != null ? ref1$ : this.update, this.error = (ref1$ = ref$.error) != null ? ref1$ : this.error; this.stop(); sessions = {}; dirs = this.recursive && this.findDir(this.path) || [this.path]; return this.watchers = dirs.map(function(dir){ return fs.watch(dir).on('error', bind$(this$, 'error')).on('change', function(type, name){ var file, ref$, timer, timeStamp, expired, time; file = path.join(dir, name); ref$ = (ref$ = sessions[file]) != null ? ref$ : sessions[file] = { timeStamp: Date.now() }, timer = ref$.timer, timeStamp = ref$.timeStamp; if (timer != null) { clearTimeout(timer); } expired = function(){ delete sessions[file]; return this$.update(type, file); }; time = this$.delay - (Date.now() - timeStamp); return sessions[file].timer = setTimeout(expired, time); }); }); }; prototype.stop = function(){ this.watchers.forEach(function(it){ return it.close(); }); return this.watchers = []; }; return RecursiveWatcher; }()); out$.RecursiveWatcher = RecursiveWatcher; function bind$(obj, key, target){ return function(){ return (target || obj)[key].apply(obj, arguments) }; } }).call(this);