javascriptnode.jsnode-red

Adding npm reference into a custom node in NodeRed


For the first time, I'm creating a custom node in NodeRed. I'm also pretty new to the NodeJs/npm world, so I may be asking for something trivial, but I could not find an answer.

I'm following the official doc for creating a doc (Creating your first node), and everything works as expected until my code is straightforward:

module.exports = function(RED) {
    function NewNode(config) {
        RED.nodes.createNode(this, config);

        var node = this;
        node.on('input', function (msg) {

            // My silly custom code
            this.warn("Something happened you should know about");

            var msg = { payload: "whatever" }
            node.send(msg);

        });
    }
    RED.nodes.registerType("custom-node", NewNode);
}

but now I would like this node to do more, like using the Axios library to make an HTTP call.

I tried to import it initially or inside the function, but it errors. Where should I "add references" to use the object inside my logic?

I tried to do the following:

const axios = require('axios');

module.exports = function(RED) {
    function NewNode(config) {
        RED.nodes.createNode(this, config);
.....

or

module.exports = function(RED) {
    function NewNode(config) {
        RED.nodes.createNode(this, config);

        var node = this;
        node.on('input', function (msg) {
             const axios = require('axios');
.....

In all cases, it errors out the moment I bring my custom node in the Flow.

Where should I import the required package?

Thanks!


Solution

  • The problem is not with the code you have shown (but the first version is more efficient).

    You need to use npm to install axios in the directory where you are creating the node so that axios gets added to its package.json as a dependency