Getting "TypeError: global.get is not a function" when trying to use an NPM package

I'm trying to use the phoenix-channels package on npm inside a node that I'm creating. I'm following the instructions. I've got it working fine in nodejs on its own.

const { Socket } = require('phoenix-channels')

let socket = new Socket("https://192.168.1.113:4445/socket")

socket.connect()

// Now that you are connected, you can join channels with a topic:
let channel = socket.channel("room:lobby", {})

channel.on("new_msg", payload => {
  console.log(`${payload.body}`);
});

channel.join()
  .receive("ok", resp => { console.log("Joined successfully", resp) })
  .receive("error", resp => { console.log("Unable to join", resp) })

I've installed phoenix channels under the ~/.node-red and I can see it:

I've added it to my settings.js file:
image

Now the instructions say I can use it by referencing the "phxModule" which is how I named it in the above settings.js file. My node does appear in the editor, but I get this error:

Now (and I'm not a javascript expert), what's wrong with the node code that I'm using? I thought I was supposed to, as per the instructions linked above, reference it using global.get?

🦎tbrowne@nano:~/code/node-red-nodes/phoenix$ cat phoenix.js
module.exports = function(RED) {
  function PhoenixNode(config) {
    RED.nodes.createNode(this,config);
    var node = this;
    
    node.on('input', function(msg) {
        msg.payload = msg.payload.toLowerCase();
        node.send(msg);
    });

    const { Socket } = global.get('phxModule');
    let socket = new Socket("https://192.168.1.113:4445/socket");
    socket.connect();
    let channel = socket.channel("room:lobby", {});
    console.log("hello from phoenix node");
    channel.on("new_msg", payload => {
      node.send({"payload": payload});
    });
    channel.join()
      .receive("ok", resp => { node.send({"payload": resp}) })
      .receive("error", resp => { node.send({"payload": "Unable to join"}) })
  }

  RED.nodes.registerType("phoenix",PhoenixNode);
}

Why am I getting this TypeError: global.get is not a function issue?

Hi,

I am guessing as I have never created a module however I think to access the contexts you would need to do

const globalContext = node.context().global
const { Socket } = globalContext.get('phxModule');

I am not sure but give it a go

Chris

1 Like

The functionGlobalContext object is used to expose modules to the Function node.

If you are creating a custom node, you can require it directly in your code - do not use global context.

2 Likes

Nick, thanks - Is this documented ? - I could not see it in the creating nodes section of the documentation. Happy to create a pull request to add if appropriate

Chris

1 Like

agreed. This wasn't clear in my (admittedly new user) opinion.

works like a dream! Now Elixir Phoenix channels can talk to Node Red. Might doll up this node and publish it once I've added all the bells and whistles!

1 Like