[CCSDK-28] populated the seed code for dgbuilder
[ccsdk/distribution.git] / dgbuilder / core_nodes / io / 23-watch.js
1 /**
2  * Copyright 2013 IBM Corp.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  **/
16
17 module.exports = function(RED) {
18     "use strict";
19     var Notify = require("fs.notify");
20     var fs = require("fs");
21     var sep = require("path").sep;
22
23     function WatchNode(n) {
24         RED.nodes.createNode(this,n);
25
26         this.files = n.files.split(",");
27         for (var f =0; f < this.files.length; f++) {
28             this.files[f] = this.files[f].trim();
29         }
30         this.p = (this.files.length == 1) ? this.files[0] : JSON.stringify(this.files);
31         var node = this;
32
33         var notifications = new Notify(node.files);
34         notifications.on('change', function (file, event, path) {
35             try {
36                 if (fs.statSync(path).isDirectory()) { path = path + sep + file; }
37             } catch(e) { }
38             var msg = { payload: path, topic: node.p, file: file };
39             node.send(msg);
40         });
41
42         notifications.on('error', function (error, path) {
43             node.warn(error);
44         });
45
46         this.close = function() {
47             notifications.close();
48         }
49     }
50     RED.nodes.registerType("watch",WatchNode);
51 }