Adding npm module and using it


#1

I want to use the atob function to convert base64 to hex. After googling a little bit I found out that npm modules can be added manually.

I did npm i atob in the npm directory, as well as the node-red directory:

usr/lib/node_modules/npm/node_modules/atob
usr/lib/node_modules/node-red/node_modules/atob

Next, I added the following to settings.js:

functionGlobalContext: {
atob: require('atob)
}

In my function node, I added the first line

var atob = global.get('atob');
var raw = "oAAABTUAAg==";
var hex = atob(raw);

But I get the following error: "TypeError: atob is not a function"

What am I doing wrong and/or misinterpreting?


#2

You need to run the npm install atob command in the same directory as your settings file.


#3

though we do have a base64 node to do conversions already - node-red-node-base64


#4

Thanks, that did the trick! (node-red-node-base64)


#5

Another way to do this, say inside some existing function code, is with the built-in JS Buffer functions:

var encoded = Buffer.from(msg.payload).toString("base64");
var decoded = Buffer.from(encoded, "base64").toString();


#6

As a last resort if you want to install atob from npm then it should work (it did for me) if you correct the missing quote in the require line in settings.js:

functionGlobalContext: {
atob: require('atob')
}