1
0
mirror of https://github.com/node-red/node-red.git synced 2023-10-10 13:36:53 +02:00

Add "use strict" to most core nodes.

(skipping ones that may have other work in progress)
This commit is contained in:
Dave C-J 2014-05-29 22:13:21 +01:00
parent 7ad28de52a
commit 2cdaed1325
22 changed files with 128 additions and 99 deletions

View File

@ -15,12 +15,13 @@
**/ **/
module.exports = function(RED) { module.exports = function(RED) {
"use strict";
var sentiment = require('sentiment'); var sentiment = require('sentiment');
function SentimentNode(n) { function SentimentNode(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
var node = this; var node = this;
this.on("input", function(msg) { this.on("input", function(msg) {
sentiment(msg.payload, msg.overrides || null, function (err, result) { sentiment(msg.payload, msg.overrides || null, function (err, result) {
msg.sentiment = result; msg.sentiment = result;

View File

@ -15,6 +15,7 @@
**/ **/
module.exports = function(RED) { module.exports = function(RED) {
"use strict";
var mustache = require("mustache"); var mustache = require("mustache");
var util = require("util"); var util = require("util");
var fs = require('fs'); var fs = require('fs');

View File

@ -15,6 +15,7 @@
**/ **/
module.exports = function(RED) { module.exports = function(RED) {
"use strict";
function CommentNode(n) { function CommentNode(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
} }

View File

@ -15,6 +15,7 @@
**/ **/
module.exports = function(RED) { module.exports = function(RED) {
"use strict";
function UnknownNode(n) { function UnknownNode(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
} }

View File

@ -15,6 +15,7 @@
**/ **/
module.exports = function(RED) { module.exports = function(RED) {
"use strict";
var util = require("util"); var util = require("util");
var exec = require('child_process').exec; var exec = require('child_process').exec;
var fs = require('fs'); var fs = require('fs');

View File

@ -102,7 +102,7 @@
<script type="text/x-red" data-template-name="mqtt-broker"> <script type="text/x-red" data-template-name="mqtt-broker">
<div class="form-row node-input-broker"> <div class="form-row node-input-broker">
<label for="node-config-input-broker"><i class="icon-bookmark"></i> Broker</label> <label for="node-config-input-broker"><i class="icon-bookmark"></i> Broker</label>
<input class="input-append-left" type="text" id="node-config-input-broker" placeholder="Broker" style="width: 40%;" > <input class="input-append-left" type="text" id="node-config-input-broker" placeholder="localhost" style="width: 40%;" >
<label for="node-config-input-port" style="margin-left: 10px; width: 35px; "> Port</label> <label for="node-config-input-port" style="margin-left: 10px; width: 35px; "> Port</label>
<input type="text" id="node-config-input-port" placeholder="Port" style="width:45px"> <input type="text" id="node-config-input-port" placeholder="Port" style="width:45px">
</div> </div>
@ -124,7 +124,7 @@
RED.nodes.registerType('mqtt-broker',{ RED.nodes.registerType('mqtt-broker',{
category: 'config', category: 'config',
defaults: { defaults: {
broker: {value:"localhost",required:true}, broker: {value:"",required:true},
port: {value:1883,required:true,validate:RED.validators.number()}, port: {value:1883,required:true,validate:RED.validators.number()},
clientid: { value:"" } clientid: { value:"" }
//user -> credentials //user -> credentials
@ -132,6 +132,7 @@
}, },
label: function() { label: function() {
if (this.broker == "") { this.broker = "localhost"; }
return (this.clientid?this.clientid+"@":"")+this.broker+":"+this.port; return (this.clientid?this.clientid+"@":"")+this.broker+":"+this.port;
}, },
oneditprepare: function() { oneditprepare: function() {
@ -144,10 +145,10 @@
} else { } else {
$('#node-config-input-pass').val(''); $('#node-config-input-pass').val('');
} }
}); });
}, },
oneditsave: function() { oneditsave: function() {
if (this.broker == "") { this.broker = "localhost"; }
var newUser = $('#node-config-input-user').val(); var newUser = $('#node-config-input-user').val();
var newPass = $('#node-config-input-pass').val(); var newPass = $('#node-config-input-pass').val();
var credentials = {}; var credentials = {};

View File

@ -15,51 +15,51 @@
**/ **/
module.exports = function(RED) { module.exports = function(RED) {
"use strict";
var ws = require("ws"), var ws = require("ws"),
inspect = require("sys").inspect; inspect = require("sys").inspect;
// A node red node that sets up a local websocket server // A node red node that sets up a local websocket server
function WebSocketListenerNode(n) { function WebSocketListenerNode(n) {
// Create a RED node // Create a RED node
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
var node = this; var node = this;
// Store local copies of the node configuration (as defined in the .html) // Store local copies of the node configuration (as defined in the .html)
node.path = n.path; node.path = n.path;
node.wholemsg = (n.wholemsg === "true"); node.wholemsg = (n.wholemsg === "true");
node._inputNodes = []; // collection of nodes that want to receive events node._inputNodes = []; // collection of nodes that want to receive events
var path = RED.settings.httpNodeRoot || "/"; var path = RED.settings.httpNodeRoot || "/";
path = path + (path.slice(-1) == "/" ? "":"/") + (node.path.charAt(0) == "/" ? node.path.substring(1) : node.path); path = path + (path.slice(-1) == "/" ? "":"/") + (node.path.charAt(0) == "/" ? node.path.substring(1) : node.path);
// Workaround https://github.com/einaros/ws/pull/253 // Workaround https://github.com/einaros/ws/pull/253
// Listen for 'newListener' events from RED.server // Listen for 'newListener' events from RED.server
node._serverListeners = {}; node._serverListeners = {};
var storeListener = function(/*String*/event,/*function*/listener){ var storeListener = function(/*String*/event,/*function*/listener){
if(event == "error" || event == "upgrade" || event == "listening"){ if(event == "error" || event == "upgrade" || event == "listening"){
node._serverListeners[event] = listener; node._serverListeners[event] = listener;
} }
} }
node._clients = {}; node._clients = {};
RED.server.addListener('newListener',storeListener); RED.server.addListener('newListener',storeListener);
// Create a WebSocket Server // Create a WebSocket Server
node.server = new ws.Server({server:RED.server,path:path}); node.server = new ws.Server({server:RED.server,path:path});
// Workaround https://github.com/einaros/ws/pull/253 // Workaround https://github.com/einaros/ws/pull/253
// Stop listening for new listener events // Stop listening for new listener events
RED.server.removeListener('newListener',storeListener); RED.server.removeListener('newListener',storeListener);
node.server.on('connection', function(socket){ node.server.on('connection', function(socket){
var id = (1+Math.random()*4294967295).toString(16); var id = (1+Math.random()*4294967295).toString(16);
node._clients[id] = socket; node._clients[id] = socket;
socket.on('close',function() { socket.on('close',function() {
delete node._clients[id]; delete node._clients[id];
}); });
@ -70,7 +70,7 @@ module.exports = function(RED) {
node.warn("An error occured on the ws connection: "+inspect(err)); node.warn("An error occured on the ws connection: "+inspect(err));
}); });
}); });
node.on("close", function() { node.on("close", function() {
// Workaround https://github.com/einaros/ws/pull/253 // Workaround https://github.com/einaros/ws/pull/253
// Remove listeners from RED.server // Remove listeners from RED.server
@ -82,17 +82,17 @@ module.exports = function(RED) {
} }
} }
node._serverListeners = {}; node._serverListeners = {};
node.server.close(); node.server.close();
node._inputNodes = []; node._inputNodes = [];
}); });
} }
RED.nodes.registerType("websocket-listener",WebSocketListenerNode); RED.nodes.registerType("websocket-listener",WebSocketListenerNode);
WebSocketListenerNode.prototype.registerInputNode = function(/*Node*/handler){ WebSocketListenerNode.prototype.registerInputNode = function(/*Node*/handler){
this._inputNodes.push(handler); this._inputNodes.push(handler);
} }
WebSocketListenerNode.prototype.handleEvent = function(id,/*socket*/socket,/*String*/event,/*Object*/data,/*Object*/flags){ WebSocketListenerNode.prototype.handleEvent = function(id,/*socket*/socket,/*String*/event,/*Object*/data,/*Object*/flags){
var msg; var msg;
if (this.wholemsg) { if (this.wholemsg) {
@ -103,25 +103,25 @@ module.exports = function(RED) {
}; };
} }
msg._session = {type:"websocket",id:id}; msg._session = {type:"websocket",id:id};
for (var i = 0; i < this._inputNodes.length; i++) { for (var i = 0; i < this._inputNodes.length; i++) {
this._inputNodes[i].send(msg); this._inputNodes[i].send(msg);
}; };
} }
WebSocketListenerNode.prototype.broadcast = function(data){ WebSocketListenerNode.prototype.broadcast = function(data){
for(var i in this.server.clients){ for(var i in this.server.clients){
this.server.clients[i].send(data); this.server.clients[i].send(data);
}; };
} }
WebSocketListenerNode.prototype.send = function(id,data){ WebSocketListenerNode.prototype.send = function(id,data){
var session = this._clients[id]; var session = this._clients[id];
if (session) { if (session) {
session.send(data); session.send(data);
} }
} }
function WebSocketInNode(n) { function WebSocketInNode(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
this.server = n.server; this.server = n.server;
@ -134,7 +134,7 @@ module.exports = function(RED) {
} }
} }
RED.nodes.registerType("websocket in",WebSocketInNode); RED.nodes.registerType("websocket in",WebSocketInNode);
function WebSocketOutNode(n) { function WebSocketOutNode(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
var node = this; var node = this;

View File

@ -15,13 +15,14 @@
**/ **/
module.exports = function(RED) { module.exports = function(RED) {
"use strict";
var notify = require("fs.notify"); var notify = require("fs.notify");
var fs = require("fs"); var fs = require("fs");
var sep = require("path").sep; var sep = require("path").sep;
function WatchNode(n) { function WatchNode(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
this.files = n.files.split(","); this.files = n.files.split(",");
for (var f in this.files) { for (var f in this.files) {
this.files[f] = this.files[f].trim(); this.files[f] = this.files[f].trim();
@ -34,7 +35,7 @@ module.exports = function(RED) {
var msg = { payload: path, topic: node.p, file: file}; var msg = { payload: path, topic: node.p, file: file};
node.send(msg); node.send(msg);
}); });
this.close = function() { this.close = function() {
notifications.close(); notifications.close();
} }

View File

@ -15,8 +15,9 @@
**/ **/
module.exports = function(RED) { module.exports = function(RED) {
"use strict";
var dgram = require('dgram'); var dgram = require('dgram');
// The Input Node // The Input Node
function UDPin(n) { function UDPin(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
@ -26,18 +27,18 @@ module.exports = function(RED) {
this.iface = n.iface || null; this.iface = n.iface || null;
this.multicast = n.multicast; this.multicast = n.multicast;
var node = this; var node = this;
var server = dgram.createSocket('udp4'); var server = dgram.createSocket('udp4');
server.on("error", function (err) { server.on("error", function (err) {
if ((err.code == "EACCES") && (node.port < 1024)) { if ((err.code == "EACCES") && (node.port < 1024)) {
node.error("UDP access error, you may need root access for ports below 1024"); node.error("UDP access error, you may need root access for ports below 1024");
} else { } else {
node.error("UDP error : "+err.code); node.error("UDP error : "+err.code);
} }
server.close(); server.close();
}); });
server.on('message', function (message, remote) { server.on('message', function (message, remote) {
var msg; var msg;
if (node.datatype =="base64") { if (node.datatype =="base64") {
@ -49,7 +50,7 @@ module.exports = function(RED) {
} }
node.send(msg); node.send(msg);
}); });
server.on('listening', function () { server.on('listening', function () {
var address = server.address(); var address = server.address();
node.log('udp listener at ' + address.address + ":" + address.port); node.log('udp listener at ' + address.address + ":" + address.port);
@ -60,7 +61,7 @@ module.exports = function(RED) {
server.addMembership(node.group,node.iface); server.addMembership(node.group,node.iface);
node.log("udp multicast group "+node.group); node.log("udp multicast group "+node.group);
} catch (e) { } catch (e) {
if (e.errno == "EINVAL") { if (e.errno == "EINVAL") {
node.error("Bad Multicast Address"); node.error("Bad Multicast Address");
} else if (e.errno == "ENODEV") { } else if (e.errno == "ENODEV") {
node.error("Must be ip address of the required interface"); node.error("Must be ip address of the required interface");
@ -70,7 +71,7 @@ module.exports = function(RED) {
} }
} }
}); });
node.on("close", function() { node.on("close", function() {
try { try {
server.close(); server.close();
@ -79,12 +80,12 @@ module.exports = function(RED) {
node.error(err); node.error(err);
} }
}); });
server.bind(node.port,node.iface); server.bind(node.port,node.iface);
} }
RED.nodes.registerType("udp in",UDPin); RED.nodes.registerType("udp in",UDPin);
// The Output Node // The Output Node
function UDPout(n) { function UDPout(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
@ -96,9 +97,9 @@ module.exports = function(RED) {
this.iface = n.iface || null; this.iface = n.iface || null;
this.multicast = n.multicast; this.multicast = n.multicast;
var node = this; var node = this;
var sock = dgram.createSocket('udp4'); // only use ipv4 for now var sock = dgram.createSocket('udp4'); // only use ipv4 for now
if (node.multicast != "false") { if (node.multicast != "false") {
if (node.outport == "") { node.outport = node.port; } if (node.outport == "") { node.outport = node.port; }
sock.bind(node.outport, function() { // have to bind before you can enable broadcast... sock.bind(node.outport, function() { // have to bind before you can enable broadcast...
@ -127,7 +128,7 @@ module.exports = function(RED) {
} else { } else {
node.log('udp ready : '+node.addr+":"+node.port); node.log('udp ready : '+node.addr+":"+node.port);
} }
node.on("input", function(msg) { node.on("input", function(msg) {
if (msg.payload != null) { if (msg.payload != null) {
var add = node.addr || msg.ip || ""; var add = node.addr || msg.ip || "";
@ -155,7 +156,7 @@ module.exports = function(RED) {
} }
} }
}); });
node.on("close", function() { node.on("close", function() {
try { try {
sock.close(); sock.close();

View File

@ -15,6 +15,7 @@
**/ **/
module.exports = function(RED) { module.exports = function(RED) {
"use strict";
var operators = { var operators = {
'eq': function(a, b) { return a == b; }, 'eq': function(a, b) { return a == b; },
'neq': function(a, b) { return a != b; }, 'neq': function(a, b) { return a != b; },
@ -31,7 +32,7 @@ module.exports = function(RED) {
'nnull': function(a) { return typeof a != "undefined"; }, 'nnull': function(a) { return typeof a != "undefined"; },
'else': function(a) { return a === true; } 'else': function(a) { return a === true; }
}; };
function SwitchNode(n) { function SwitchNode(n) {
RED.nodes.createNode(this, n); RED.nodes.createNode(this, n);
this.rules = n.rules; this.rules = n.rules;
@ -39,7 +40,7 @@ module.exports = function(RED) {
this.checkall = n.checkall || "true"; this.checkall = n.checkall || "true";
var propertyParts = n.property.split("."), var propertyParts = n.property.split("."),
node = this; node = this;
for (var i=0; i<this.rules.length; i+=1) { for (var i=0; i<this.rules.length; i+=1) {
var rule = this.rules[i]; var rule = this.rules[i];
if (!isNaN(Number(rule.v))) { if (!isNaN(Number(rule.v))) {
@ -47,7 +48,7 @@ module.exports = function(RED) {
rule.v2 = Number(rule.v2); rule.v2 = Number(rule.v2);
} }
} }
this.on('input', function (msg) { this.on('input', function (msg) {
var onward = []; var onward = [];
var prop = propertyParts.reduce(function (obj, i) { var prop = propertyParts.reduce(function (obj, i) {

View File

@ -15,6 +15,7 @@
**/ **/
module.exports = function(RED) { module.exports = function(RED) {
"use strict";
function ChangeNode(n) { function ChangeNode(n) {
RED.nodes.createNode(this, n); RED.nodes.createNode(this, n);
this.action = n.action; this.action = n.action;
@ -34,7 +35,7 @@ module.exports = function(RED) {
if (lastPart) { stem = stem[lastPart] = value; } if (lastPart) { stem = stem[lastPart] = value; }
return stem; return stem;
}; };
this.on('input', function (msg) { this.on('input', function (msg) {
if (node.action == "change") { if (node.action == "change") {
try { try {

View File

@ -15,6 +15,7 @@
**/ **/
module.exports = function(RED) { module.exports = function(RED) {
"use strict";
function RangeNode(n) { function RangeNode(n) {
RED.nodes.createNode(this, n); RED.nodes.createNode(this, n);
this.action = n.action; this.action = n.action;
@ -24,7 +25,7 @@ module.exports = function(RED) {
this.minout = Number(n.minout); this.minout = Number(n.minout);
this.maxout = Number(n.maxout); this.maxout = Number(n.maxout);
var node = this; var node = this;
this.on('input', function (msg) { this.on('input', function (msg) {
var n = Number(msg.payload); var n = Number(msg.payload);
if (!isNaN(n)) { if (!isNaN(n)) {

View File

@ -15,6 +15,7 @@
**/ **/
module.exports = function(RED) { module.exports = function(RED) {
"use strict";
function CSVNode(n) { function CSVNode(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
this.template = n.temp.split(","); this.template = n.temp.split(",");

View File

@ -15,8 +15,9 @@
**/ **/
module.exports = function(RED) { module.exports = function(RED) {
"use strict";
var util = require("util"); var util = require("util");
function JSONNode(n) { function JSONNode(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
var node = this; var node = this;

View File

@ -15,10 +15,11 @@
**/ **/
module.exports = function(RED) { module.exports = function(RED) {
"use strict";
var xml2js = require('xml2js'); var xml2js = require('xml2js');
var parseString = xml2js.parseString; var parseString = xml2js.parseString;
var builder = new xml2js.Builder({renderOpts:{pretty:false}}); var builder = new xml2js.Builder({renderOpts:{pretty:false}});
function XMLNode(n) { function XMLNode(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
var node = this; var node = this;

View File

@ -15,9 +15,10 @@
**/ **/
module.exports = function(RED) { module.exports = function(RED) {
"use strict";
var FeedParser = require("feedparser"); var FeedParser = require("feedparser");
var request = require("request"); var request = require("request");
function FeedParseNode(n) { function FeedParseNode(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
this.url = n.url; this.url = n.url;
@ -54,18 +55,17 @@ module.exports = function(RED) {
}; };
this.interval_id = setInterval(getFeed,node.interval); this.interval_id = setInterval(getFeed,node.interval);
getFeed(); getFeed();
} else { } else {
this.error("Invalid url"); this.error("Invalid url");
} }
} }
RED.nodes.registerType("feedparse",FeedParseNode); RED.nodes.registerType("feedparse",FeedParseNode);
FeedParseNode.prototype.close = function() { FeedParseNode.prototype.close = function() {
if (this.interval_id != null) { if (this.interval_id != null) {
clearInterval(this.interval_id); clearInterval(this.interval_id);
} }
} }
} }

View File

@ -15,6 +15,7 @@
**/ **/
module.exports = function(RED) { module.exports = function(RED) {
"use strict";
var util = require('util'); var util = require('util');
var nodemailer = require("nodemailer"); var nodemailer = require("nodemailer");
var Imap = null; var Imap = null;

View File

@ -15,9 +15,10 @@
**/ **/
module.exports = function(RED) { module.exports = function(RED) {
"use strict";
var irc = require("irc"); var irc = require("irc");
var util = require("util"); var util = require("util");
// The Server Definition - this opens (and closes) the connection // The Server Definition - this opens (and closes) the connection
function IRCServerNode(n) { function IRCServerNode(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
@ -32,8 +33,8 @@ module.exports = function(RED) {
}); });
} }
RED.nodes.registerType("irc-server",IRCServerNode); RED.nodes.registerType("irc-server",IRCServerNode);
// The Input Node // The Input Node
function IrcInNode(n) { function IrcInNode(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
@ -50,7 +51,7 @@ module.exports = function(RED) {
} }
this.ircclient = this.serverConfig.ircclient; this.ircclient = this.serverConfig.ircclient;
var node = this; var node = this;
this.ircclient.addListener('message', function (from, to, message) { this.ircclient.addListener('message', function (from, to, message) {
//util.log(from + ' => ' + to + ': ' + message); //util.log(from + ' => ' + to + ': ' + message);
var msg = { "topic":from, "from":from, "to":to, "payload":message }; var msg = { "topic":from, "from":from, "to":to, "payload":message };
@ -60,7 +61,7 @@ module.exports = function(RED) {
var msg = { "topic":from, "from":from, "to":"PRIV", "payload":message }; var msg = { "topic":from, "from":from, "to":"PRIV", "payload":message };
node.send([msg,null]); node.send([msg,null]);
}); });
this.ircclient.addListener('join', function(channel, who) { this.ircclient.addListener('join', function(channel, who) {
var msg = { "payload": { "type":"join", "who":who, "channel":channel } }; var msg = { "payload": { "type":"join", "who":who, "channel":channel } };
node.send([null,msg]); node.send([null,msg]);
@ -90,11 +91,11 @@ module.exports = function(RED) {
var msg = { "payload": { "type": "names", "channel": channel, "names": nicks} }; var msg = { "payload": { "type": "names", "channel": channel, "names": nicks} };
node.send([null, msg]); node.send([null, msg]);
}); });
} }
RED.nodes.registerType("irc in",IrcInNode); RED.nodes.registerType("irc in",IrcInNode);
// The Output Node // The Output Node
function IrcOutNode(n) { function IrcOutNode(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
@ -112,7 +113,7 @@ module.exports = function(RED) {
} }
this.ircclient = this.serverConfig.ircclient; this.ircclient = this.serverConfig.ircclient;
var node = this; var node = this;
this.on("input", function(msg) { this.on("input", function(msg) {
if (Object.prototype.toString.call( msg.raw ) === '[object Array]') { if (Object.prototype.toString.call( msg.raw ) === '[object Array]') {
var m = msg.raw; var m = msg.raw;

View File

@ -15,16 +15,17 @@
**/ **/
module.exports = function(RED) { module.exports = function(RED) {
"use strict";
var fs = require("fs"); var fs = require("fs");
var spawn = require('child_process').spawn; var spawn = require('child_process').spawn;
function TailNode(n) { function TailNode(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
this.filename = n.filename; this.filename = n.filename;
this.split = n.split; this.split = n.split;
var node = this; var node = this;
var err = ""; var err = "";
var tail = spawn("tail", ["-f", this.filename]); var tail = spawn("tail", ["-f", this.filename]);
tail.stdout.on("data", function (data) { tail.stdout.on("data", function (data) {
@ -43,15 +44,15 @@ module.exports = function(RED) {
node.send(msg); node.send(msg);
} }
}); });
tail.stderr.on("data", function(data) { tail.stderr.on("data", function(data) {
node.warn(data.toString()); node.warn(data.toString());
}); });
this.on("close", function() { this.on("close", function() {
if (tail) tail.kill(); if (tail) tail.kill();
}); });
} }
RED.nodes.registerType("tail",TailNode); RED.nodes.registerType("tail",TailNode);
} }

View File

@ -15,18 +15,19 @@
**/ **/
module.exports = function(RED) { module.exports = function(RED) {
"use strict";
var fs = require("fs"); var fs = require("fs");
function FileNode(n) { function FileNode(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
this.filename = n.filename; this.filename = n.filename;
this.appendNewline = n.appendNewline; this.appendNewline = n.appendNewline;
this.overwriteFile = n.overwriteFile; this.overwriteFile = n.overwriteFile;
var node = this; var node = this;
this.on("input",function(msg) { this.on("input",function(msg) {
var filename = msg.filename || this.filename; var filename = msg.filename || this.filename;
if (filename == "") { if (filename == "") {
node.warn('No filename specified'); node.warn('No filename specified');
} else if (typeof msg.payload != "undefined") { } else if (typeof msg.payload != "undefined") {
@ -60,10 +61,10 @@ module.exports = function(RED) {
}); });
} }
RED.nodes.registerType("file",FileNode); RED.nodes.registerType("file",FileNode);
function FileInNode(n) { function FileInNode(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
this.filename = n.filename; this.filename = n.filename;
this.format = n.format; this.format = n.format;
var node = this; var node = this;
@ -73,7 +74,7 @@ module.exports = function(RED) {
} }
this.on("input",function(msg) { this.on("input",function(msg) {
var filename = msg.filename || this.filename; var filename = msg.filename || this.filename;
if (filename == "") { if (filename == "") {
node.warn('No filename specified'); node.warn('No filename specified');
} else { } else {

View File

@ -105,9 +105,10 @@
<div class="form-row"> <div class="form-row">
<label for="node-input-operation"><i class="icon-wrench"></i> Operation</label> <label for="node-input-operation"><i class="icon-wrench"></i> Operation</label>
<select type="text" id="node-input-operation" style="display: inline-block; vertical-align: top;"> <select type="text" id="node-input-operation" style="display: inline-block; vertical-align: top;">
<option value=store>save</option> <option value="store">save</option>
<option value=insert>insert</option> <option value="insert">insert</option>
<option value=delete>remove</option> <option value="update">update</option>
<option value="delete">remove</option>
</select> </select>
</div> </div>
<div class="form-row node-input-payonly"> <div class="form-row node-input-payonly">

View File

@ -15,9 +15,10 @@
**/ **/
module.exports = function(RED) { module.exports = function(RED) {
"use strict";
var mongo = require('mongodb'); var mongo = require('mongodb');
var MongoClient = mongo.MongoClient; var MongoClient = mongo.MongoClient;
function MongoNode(n) { function MongoNode(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
this.hostname = n.hostname; this.hostname = n.hostname;
@ -29,20 +30,20 @@ module.exports = function(RED) {
this.username = credentials.user; this.username = credentials.user;
this.password = credentials.password; this.password = credentials.password;
} }
var url = "mongodb://"; var url = "mongodb://";
if (this.username && this.password) { if (this.username && this.password) {
url += this.username+":"+this.password+"@"; url += this.username+":"+this.password+"@";
} }
url += this.hostname+":"+this.port+"/"+this.db; url += this.hostname+":"+this.port+"/"+this.db;
this.url = url; this.url = url;
} }
RED.nodes.registerType("mongodb",MongoNode); RED.nodes.registerType("mongodb",MongoNode);
var querystring = require('querystring'); var querystring = require('querystring');
RED.httpAdmin.get('/mongodb/:id',function(req,res) { RED.httpAdmin.get('/mongodb/:id',function(req,res) {
var credentials = RED.nodes.getCredentials(req.params.id); var credentials = RED.nodes.getCredentials(req.params.id);
if (credentials) { if (credentials) {
@ -51,12 +52,12 @@ module.exports = function(RED) {
res.send(JSON.stringify({})); res.send(JSON.stringify({}));
} }
}); });
RED.httpAdmin.delete('/mongodb/:id',function(req,res) { RED.httpAdmin.delete('/mongodb/:id',function(req,res) {
RED.nodes.deleteCredentials(req.params.id); RED.nodes.deleteCredentials(req.params.id);
res.send(200); res.send(200);
}); });
RED.httpAdmin.post('/mongodb/:id',function(req,res) { RED.httpAdmin.post('/mongodb/:id',function(req,res) {
var body = ""; var body = "";
req.on('data', function(chunk) { req.on('data', function(chunk) {
@ -79,8 +80,8 @@ module.exports = function(RED) {
res.send(200); res.send(200);
}); });
}); });
function MongoOutNode(n) { function MongoOutNode(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
this.collection = n.collection; this.collection = n.collection;
@ -88,7 +89,7 @@ module.exports = function(RED) {
this.payonly = n.payonly || false; this.payonly = n.payonly || false;
this.operation = n.operation; this.operation = n.operation;
this.mongoConfig = RED.nodes.getNode(this.mongodb); this.mongoConfig = RED.nodes.getNode(this.mongodb);
if (this.mongoConfig) { if (this.mongoConfig) {
var node = this; var node = this;
MongoClient.connect(this.mongoConfig.url, function(err,db) { MongoClient.connect(this.mongoConfig.url, function(err,db) {
@ -116,6 +117,15 @@ module.exports = function(RED) {
coll.insert(msg,function(err,item){if (err){node.error(err);}}); coll.insert(msg,function(err,item){if (err){node.error(err);}});
} }
} }
else if (node.operation == "update") {
delete msg._topic;
if (node.payonly) {
if (typeof msg.payload !== "object") { msg.payload = {"payload":msg.payload}; }
coll.update(msg.payload,function(err,item){ if (err){node.error(err);} });
} else {
coll.update(msg,function(err,item){if (err){node.error(err);}});
}
}
if (node.operation == "delete") { if (node.operation == "delete") {
coll.remove(msg.payload, {w:1}, function(err, items){ if (err) node.error(err); }); coll.remove(msg.payload, {w:1}, function(err, items){ if (err) node.error(err); });
} }
@ -125,7 +135,7 @@ module.exports = function(RED) {
} else { } else {
this.error("missing mongodb configuration"); this.error("missing mongodb configuration");
} }
this.on("close", function() { this.on("close", function() {
if (this.clientDb) { if (this.clientDb) {
this.clientDb.close(); this.clientDb.close();
@ -133,14 +143,14 @@ module.exports = function(RED) {
}); });
} }
RED.nodes.registerType("mongodb out",MongoOutNode); RED.nodes.registerType("mongodb out",MongoOutNode);
function MongoInNode(n) { function MongoInNode(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
this.collection = n.collection; this.collection = n.collection;
this.mongodb = n.mongodb; this.mongodb = n.mongodb;
this.mongoConfig = RED.nodes.getNode(this.mongodb); this.mongoConfig = RED.nodes.getNode(this.mongodb);
if (this.mongoConfig) { if (this.mongoConfig) {
var node = this; var node = this;
MongoClient.connect(this.mongoConfig.url, function(err,db) { MongoClient.connect(this.mongoConfig.url, function(err,db) {
@ -168,7 +178,7 @@ module.exports = function(RED) {
} else { } else {
this.error("missing mongodb configuration"); this.error("missing mongodb configuration");
} }
this.on("close", function() { this.on("close", function() {
if (this.clientDb) { if (this.clientDb) {
this.clientDb.close(); this.clientDb.close();