Last active
March 8, 2017 18:36
-
-
Save egasimus/26bac9120b4b1014333a2078b651b5e2 to your computer and use it in GitHub Desktop.
Self-updating Node.js module in ~39SLOC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('fs') | |
var path = require('path') | |
var vm = require('vm') | |
module.exports = { | |
watch: | |
function (module) { | |
fs.watch(module.filename, function (event, filename) { | |
module.exports.changed(module, this, event, filename); }) }, | |
changed: | |
function (module, watcher, event, filename) { | |
if (event === 'rename' && !fs.existsSync(__filename)) { | |
watcher.deleted = true; | |
return console.log("<>", "delete", filename); } | |
if (watcher.deleted) { | |
event = 'create'; | |
delete watcher.deleted } | |
console.log("<>", event, filename); | |
var source = fs.readFileSync(__filename, 'utf8'); | |
/* at this point you can transform the source using babel, etc */ | |
if (module.source === source) return console.log('no changes'); | |
module.source = source; | |
var context = module.exports.update(vm.createContext(global), | |
{ require: require | |
, module: module | |
, console: console | |
, process: process | |
, global: global | |
, __filename: __filename | |
, __dirname: __dirname }); | |
var options = { filename: __filename, displayErrors: true }; | |
vm.runInContext(source, context, options); | |
console.log(module.exports); | |
watcher.close(); }, | |
update: | |
function (into, from) { | |
for (key in from) into[key] = from[key]; | |
for (key in into) if (Object.keys(from).indexOf(key) < 0) delete into[key]; | |
return into; } } | |
module.exports.watch(module); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment