Using Moment.js in a function node - NR 3.01 - 2023?

Guys

What is the state of the nation in terms of using Moment.js in a function node as of NR 3.01 and 2023 ?

I believe that Moment.js is now included with NR due to support in the change node/jsonata etc.

What is the method therefore for calling moment in a function node for dat and time formatting ?

Having done a search on this already it appears that the solution has evolved over time and am unsure if i need to install the NPM module now, make the addition to settings.js etc - or if i can happily just declare it at the top of my function and away i go ?

Craig

You have to include it in the Setup tab of any Function node you want to use it

image

Example of formatting today's date

msg.payload = moment().format("YYYY-MM-DD HH:mm:ss")
return msg;

If an npm package is already in .node-red/node_modules, possibly because it was installed by another node, Node-red will use that when you add it in a Function's Setup tab .. if its missing it will automatically install it.

In settings.js there is the following settings to allow or deny this functionality.

  /** Allow the Function node to load additional npm modules directly */
  functionExternalModules: true,
2 Likes

You can also use JSONata in a function node - which already includes Moment of course.

I think $moment() was added to jsonata by Node-red but only available in the Change node.
The jsonata library by itself natively doesnt have it as function.

but even so .. if someone would resort to using a Function node, it means they have some knowledge of JS and i doubt they would be using jsonata which as demonstrated in some posts is a bit slower than plain JS.

It's OK because it looks like I made up that fact anyway! I was convinced that JSONata had been added as a function to function nodes but I can't find any references to it at all.

1 Like

Do you mean these?
evaluateJSONataExpression
prepareJSONataExpression

3 Likes

it works .. Interesting, never knew those existed :wink:

const expression = '$moment().format("YYYY-MM-DD HH:mm:ss")';

let exp = RED.util.prepareJSONataExpression(expression, node)

RED.util.evaluateJSONataExpression(exp, msg, (err, res) => {
    node.send({ payload : res})
})

Grrr :grin: well found. Added to my Obsidian knowledgebase as it should have been before.

Well hidden indeed.

thanks for chiming in everyone - hopefully all of that will help out the next person who wants to use moment in a simple fnction node

Much appreciated.

Craig

2 Likes

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