7

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.

DPGUITARMAN
  • 161
  • 1
  • 2
  • 12

2 Answers2

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.

Jake Peyser
  • 1,180
  • 8
  • 17
  • 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? – DPGUITARMAN Apr 22 '16 at 00:36
  • 1
    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](https://developer.ibm.com/answers/questions/20763/how-to-change-settings-in-node-red-to-allow-cors.html) on how to do that. – Jake Peyser Apr 22 '16 at 18:46
  • Worked perfectly! and I would have racked my brains on that GIT topic so thanks for that advice as well. – DPGUITARMAN Apr 23 '16 at 00:59
1
Settings file:/Users/aiquantong/.node-red/settings

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

aiquantong
  • 71
  • 3