[CCSDK-28] populated the seed code for dgbuilder
[ccsdk/distribution.git] / dgbuilder / core_nodes / parsers / 70-HTML.js
1 /**
2  * Copyright 2014 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 cheerio = require('cheerio');
20
21     function CheerioNode(n) {
22         RED.nodes.createNode(this,n);
23         this.tag = n.tag || "h1";
24         this.ret = n.ret || "html";
25         this.as = n.as || "single";
26         var node = this;
27         this.on("input", function(msg) {
28             try {
29                 var $ = cheerio.load(msg.payload);
30                 var pay = [];
31                 $(node.tag).each(function() {
32                     if (node.as === "multi") {
33                         var pay2 = null;
34                         if (node.ret === "html") { pay2 = $(this).html(); }
35                         if (node.ret === "text") { pay2 = $(this).text(); }
36                         //if (node.ret === "attr") { pay2 = $(this)[0]["attribs"]; }
37                         //if (node.ret === "val")  { pay2 = $(this).val(); }
38                         if (pay2) {
39                             msg.payload = pay2;
40                             node.send(msg);
41                         }
42                     }
43                     if (node.as === "single") {
44                         if (node.ret === "html") { pay.push( $(this).html() ); }
45                         if (node.ret === "text") { pay.push( $(this).text() ); }
46                         //if (node.ret === "attr") { pay.push( $(this)[0]["attribs"] ); }
47                         //if (node.ret === "val")  { pay.push( $(this).val() ); }
48                     }
49                 });
50                 if ((node.as === "single") && (pay.length !== 0)) {
51                     msg.payload = pay;
52                     node.send(msg);
53                 }
54             } catch (error) {
55                 node.log('Error: '+error.message);
56             }
57         });
58     }
59     RED.nodes.registerType("html",CheerioNode);
60 }