I am trying to use a npm module in node-red, after doing some research I came accross the use of global context and so I did the following:
Added a require in setting.js file of my node-red directory like so:
functionGlobalContext: { aesjs:require('aes-js'),},
Added a require to my red.js require (just in case) :
var aesjs = require('aes-js');
Installed the module
aes-js
globally and in node-red'snode_modules
directoryI would call the module in a node function by invoking the global context:
var aesjs = global.get('aesjs');
Problem is, once I execute my flow, the variable aesjs is undefined and I get the following debugging message:
"TypeError: Cannot read property 'ModeOfOperation' of undefined"
Which is in reference to the following code:
var aesjs = global.get('aesjs');
var aesEcb = new aesjs.ModeOfOperation.ecb(key);
In essence, I relied on this post but can't seem to understand why the variable is undefined, is it an issue of asynchronicity, if so how?
Here's an export of my experimental flow, just to make sure not stupid mistakes have been made:
[{"id":"205673d0.6ffd3c","type":"inject","z":"6affe53a.7dabcc","name":"","topic":"","payload":"{ \"id\": \"474192\" }","payloadType":"json","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":200,"y":420,"wires":[["f2c2083b.0afae8"]]},{"id":"f2c2083b.0afae8","type":"function","z":"6affe53a.7dabcc","name":"encrypt clientUid","func":"var aesjs = context.global.get('aesjs');\nvar gsm = msg.payload.id; \n\nvar key = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ];\n\nfunction gsmEncode(gsm,key)\n {\n var textBytes=[];\n \n for ( i = 0; i < gsm.length; ++i)\n {\n var charCode = gsm.charCodeAt(i);\n textBytes.push(charCode & 0xFF);\n }\n \n return(bytesEncode(textBytes,key));\n }\n\nfunction bytesEncode(bytes,key)\n {\n for ( i = bytes.length;i<16; ++i)\n bytes.push(0);\n \n var aesEcb = new aesjs.ModeOfOperation.ecb(key);\n var encryptedBytes = aesEcb.encrypt(bytes);\n \n return(Buffer.from(encryptedBytes).toString('base64'));\n \n }\n\nmsg.payload.encodedId = gsmEncode(gsm,key);\n\nreturn msg; ","outputs":1,"noerr":0,"x":480,"y":420,"wires":[["fab2be23.e888d"]]},{"id":"fab2be23.e888d","type":"debug","z":"6affe53a.7dabcc","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","x":810,"y":420,"wires":[]}]