-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrequire-watcher.js
33 lines (32 loc) · 1.1 KB
/
require-watcher.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
var chokidar = require('chokidar');
var path = require('path');
module.exports = function(dir){
console.log('Router watch', dir)
let rootFolder = dir
if(dir.charAt(dir.length - path.sep.length) !== path.sep) {
console.log('Testing if the folder is a folder')
rootFolder = path.dirname(dir).replace(new RegExp('\\' + path.sep, 'g'), '/')
}
var watcherlive = chokidar.watch(rootFolder)
var re = new RegExp(rootFolder)
console.log('regex created', re)
watcherlive.on('ready', function() {
watcherlive.on('all', function() {
console.log('Clearing ' + rootFolder + ' module cache from server')
Object.keys(require.cache).forEach(function(id) {
if (re.test(id.replace(new RegExp('\\' + path.sep, 'g'), '/'))) {
console.log('deleting cache key')
delete require.cache[id]
}
})
})
})
// achei em tutorial
// delete require.cache[require.resolve('./my-module')];
// const localId = id.substr(process.cwd().length);
require(dir);
return function(req, res, next) {
console.log('require hot reload')
require(dir)(req, res, next);
}
}