Using moment in function node

Hi All,

I wanted to use moment in a function node. I stumbled upon this issue which appears rather old.

I tried using the tip to add the moments to the functionGlobalContext but did not work. I did not get the error during NR startup that it does not find moments, but global.get("moment") did not return anything.

Now, I am using the function-npm node where I can use require and it works:

var moment = require('moment');

msg.payload = moment().format('MMMM Do YYYY, h:mm:ss a'); // April 27th 2020, 6:08:20 pm
return msg;

Is this still the recommended method, or did I missed some other and supported option?

Regards,
Csongor

The recommended method is still what it says in the docs - Writing Functions : Node-RED

Can you share exactly what you added to your functionGlobalContext ?

This is what it says exactly:

    functionGlobalContext: {
	moment:require('moment')
        // os:require('os'),
        // jfive:require("johnny-five"),
        // j5board:require("johnny-five").Board({repl:false})
    },

I know you mentioned before that moment could be installed in the incorrect directory. I am running NR on Windows now, and it is installed here: C:\Users\xxxxx\AppData\Roaming\npm\node_modules\node-red\node_modules\moment.

You should run the npm install moment command in the same directory as your settings.js file

I have done that now:

C:\Users\xxxxxx\AppData\Roaming\npm\node_modules\node-red>npm install moment
npm notice created a lockfile as package-lock.json. You should commit this file.
+ moment@2.24.0
updated 1 package and audited 1345 packages in 2.51s

1 package is looking for funding
  run `npm fund` for details

found 0 vulnerabilities

It is still not working, moment is undefined in the function node. Should I see something in the log when I start node-red? I mean I am not seeing any info or warning that the moment is being loaded or failed to load.

That suggests you have edited the wrong settings file. Node-RED logs the full path to the settings file it is using when it starts. Make sure you have the right one.

Sorry for all this, of course I was looking in a wrong directory.
I have re-installed npm install moment in c:\users\xxxxx\.node-red where my actual settings.js file as and now everything works. The code in my first comment works in a regular function node.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.