2 * Copyright 2013 IBM Corp.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 module.exports = function(RED) {
19 var util = require("util");
20 var vm = require("vm");
22 function FunctionNode(n) {
23 RED.nodes.createNode(this,n);
26 var functionText = "var results = null; results = (function(msg){"+this.func+"\n})(msg);";
33 global:RED.settings.functionGlobalContext || {}
36 var context = vm.createContext(sandbox);
38 this.script = vm.createScript(functionText);
39 this.on("input", function(msg) {
41 var start = process.hrtime();
43 this.script.runInContext(context);
44 var results = context.results;
45 if (results == null) {
47 } else if (results.length == null) {
51 for (var m in results) {
53 if (util.isArray(results[m])) {
54 for (var n=0; n < results[m].length; n++) {
55 results[m][n]._topic = msg._topic;
58 results[m]._topic = msg._topic;
64 var duration = process.hrtime(start);
65 if (process.env.NODE_RED_FUNCTION_TIME) {
66 this.status({fill:"yellow",shape:"dot",text:""+Math.floor((duration[0]* 1e9 + duration[1])/10000)/100});
69 this.error(err.toString());
77 RED.nodes.registerType("function",FunctionNode);
78 RED.library.register("functions");