Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'require' keyword doesn't work within Node Red Function node

first line in a Node red Function Node is

var moment = require('moment-timezone');

...

I am trying to establish a timezone correct date/time stamp for sensor data. I get the following error when this node runs;

ReferenceError: require is not defined (line 1, col 14)

This function, by the way, has other JavaScript which always runs perfectly.

My Package.json has no errors and I have the, "moment-timezone":"0.5.3" added.

I understand from a bit or research that I need to add something to the settings.js file, however, I need some guidance on what to add so that 'require' is recognized.

like image 861
DPGUITARMAN Avatar asked Apr 20 '16 23:04

DPGUITARMAN


People also ask

How does require work in node?

Node. js follows the CommonJS module system, and the built-in require function is the easiest way to include modules that exist in separate files. The basic functionality of require is that it reads a JavaScript file, executes the file, and then proceeds to return the exports object.

What is function node in Node-RED?

The Function node allows JavaScript code to be run against the messages that are passed through it. The message is passed in as an object called msg .

What language is Node-RED function?

Node-RED is built on Node. js, taking full advantage of its event-driven, non-blocking model. This makes it ideal to run at the edge of the network on low-cost hardware such as the Raspberry Pi as well as in the cloud.


2 Answers

As this GitHub issue answer states, you cannot use require itself inside a function node, but you can add external modules to the sandbox used to run functions. You would do this setting functionGlobalContext inside your settings.js file like the following:

functionGlobalContext: {
    tzModule:require('moment-timezone')
}

The module can then be referenced by using the following code:

var moment = global.get('tzModule');

Check out the Node-RED documentation on global-context for full details.

like image 104
Jake Peyser Avatar answered Nov 01 '22 10:11

Jake Peyser


Settings file:/Users/aiquantong/.node-red/settings

Please do configure in this file, it will be working.

like image 41
aiquantong Avatar answered Nov 01 '22 09:11

aiquantong