forked from fatoldsun00/node-red-contrib-watchdirectory
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode-red-watchdirectory.js
86 lines (79 loc) · 2.67 KB
/
node-red-watchdirectory.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
module.exports = function(RED) {
const chokidar = require('chokidar')
const path = require('path');
function WatchDirectory(config) {
RED.nodes.createNode(this,config);
this.folderType = config.folderType || "str"
this.folder = path.normalize(RED.util.evaluateNodeProperty(config.folder, this.folderType, this))
this.recursive = config.recursive;
this.typeEvent = config.typeEvent;
this.ignoreInitial = config.ignoreInitial;
this.ignoredFiles = config.ignoredFiles || false;
this.startListening();
}
WatchDirectory.prototype.startListening = function() {
var node = this;
// Initialize watcher.
const watcher = chokidar.watch(node.folder, {
ignored: (filename) => {
filename = path.normalize( filename )
let file = path.basename(filename)
if (file && file.length && node.ignoredFiles.length){
re = new RegExp(node.ignoredFiles)
return re.test(file)
}
},
persistent: true,
depth: node.recursive,
ignoreInitial: node.ignoreInitial,
awaitWriteFinish:true,
usePolling:true,
alwaysStat: true,
useFsEvents : true,
binaryInterval: 1000
});
let payload
switch (node.typeEvent) {
case 'create':
watcher.on('add', (filename, stats) => {
payload = node.createMSG(filename, stats)
node.send(payload)
node.status({fill:"green", shape: "dot", text: "add "+filename})
})
break;
case 'update':
watcher.on('change', (filename, stats) => {
payload = node.createMSG(filename, stats)
node.send(payload)
node.status({fill:"green", shape: "dot", text: "update "+filename})
})
break;
case 'delete':
watcher.on('unlink',(filename) => {
payload = node.createMSG(filename)
node.send(payload)
node.status({fill:"green", shape: "dot", text: "delete "+filename})
})
break;
}
watcher.on('ready', () => {
setTimeout(() => {
node.status({fill:"yellow", shape: "ring", text: "Listening..."})
}, 10000)
}).on('error', (err) => {
node.status({fill:"red", shape: "dot", text: "Error : "+err.message})
throw(err)
})
//on close
node.on('close', () => {
watcher.close()
})
}
WatchDirectory.prototype.createMSG = function(filename, stats) {
filename = path.normalize( filename )
const file = path.basename(filename)
const filedir = path.dirname(filename)
return {file,filedir,filename, payload: filename, size: stats?stats.size:0}
}
RED.nodes.registerType("watch-directory",WatchDirectory);
}