ReferenceError: SunCalc is not defined


#1

I really have no idea what I am doing :slight_smile:
I would like to use suncalc to get the sunset and sunrise times for a day.
I installed suncalc in node red and npm. The sunrise node in node red works ok. I added SunCalc:require("suncalc") to my settings .js and tried calling SunCalc in my function node but all I get is "ReferenceError: SunCalc is not defined". Could someone shed a little light here?
Thanks


#2

Why not use the node-red-node-suncalc node direct ? Check the flows.nodered.org website


#3

That would be great if I knew how :slight_smile:
How do I get the sunset and sunrise time from node-red-node-suncalc?


#4

By reading the node documentation, searching the forum.


#5

Thank you, very helpful


#6

How did you use it in your function node?

Note: https://discourse.nodered.org/t/how-to-share-code-or-flow-json/506


#7

I tried

var times = SunCalc.getTimes(new Date(), 51.5, -0.1);

and

var times = global.get(SunCalc.getTimes(new Date(), 51.5, -0.1));

Both returned "ReferenceError: SunCalc is not defined"


#8

You'd need to be a bit more specific about what you've tried.

The documentation for how to add new modules to the Function node is here: https://nodered.org/docs/writing-functions#loading-additional-modules

From what you say, I assume your SunCalc:require("suncalc") line is inside the functionGlobalContext block in the settings file.
I also assume you've actually installed the suncalc module in ~/.node-red.

In your Function node you would then do:

var SunCalc = global.get('SunCalc');
var times = SunCalc.getTimes(....)

#9

Your suggestion works, as you knew it would.
Yes, I was attempting to follow https://nodered.org/docs/writing-functions#loading-additional-modules but zero experience with javascript and node red was killing me.
My only programming knowledge is from 22 years of C on HP/UX.
Thanks


#10

If you do it that way, you don't need the node installed.

When using a node, you generally expect that the data it adds is attached to the msg object and you can then pick it up in the next node downstream. This is a generally preferred approach than adding weight to the global variable object.