'require' keyword doesn't work within Node Red Function node
Asked Answered
G

2

8

The 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.

Gadget answered 20/4, 2016 at 23:14 Comment(0)
A
13

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.

Amative answered 21/4, 2016 at 2:50 Comment(3)
Don't have a clue how to edit the settings.js file. Do I actually have to fetch it with CLI, edit locally then upload. Yikes! Even more fundamentally I started my efforts on bluemix with node red starter and have graduated to use standard nodes and the function node with my javascript. Not elegant but it all worked. When I tried to further evolve to using GIT and devops, it wouldn't copy any of that work over to the initial repository. My primarily objective here, however, is to take Jake's advice and modify the setting.js file as he instructed. What is the most graceful way to do that?Gadget
Unfortunately, the Add Git button on Bluemix will only take the starter code for your app to populate your Git repo. You would have to manually take the changes you made and apply them back to your repo. To your main question, you would need to update the bluemix-settings.js for your app to make this happen. Follow Nick's answer here on how to do that.Amative
Worked perfectly! and I would have racked my brains on that GIT topic so thanks for that advice as well.Gadget
C
1
Settings file:/Users/aiquantong/.node-red/settings

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

Cartage answered 3/1, 2018 at 10:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.