简体   繁体   中英

How to create a custom module for Node-Red for use require statement of node and require npm modules inside flows

I need help to create a custom node to use the require estatement of nodeJs in node-red, according to the documentation three files are required in a common directory:

    require
        -required.js
        -required.html
        -package.json

the package.json content is:

     {
        "name": "node-red-contrib-require",
        "node-red": {
            "nodes": {
                "require": "required.js"
            }
        }
    }

the required.html content is:

<script type="text/javascript">
    RED.nodes.registerType("require", {
        category: "function",
        color: "#a6bbcf",
        defaults: {
            name: { value: "" },
        },
        inputs: 1,
        outputs: 1,
        icon: "file.png",
        label: function () {
            return this.name || "require";
        },
    });
</script>

<script type="text/html" data-template-name="require">
    <div class="form-row">
        <label for="node-input-name"
            ><i class="fa fa-tag" aria-hidden="true"></i> Module</label
        >
        <input type="text" id="node-input-name" placeholder="Name" />
    </div>
</script>

<script type="text/html" data-help-name="required">
    <p>
        A simple node that implements the require statement of nodeJs to message
        payloads as required modules
    </p>
</script>

I don't know how to implement the code for required.js file, in NodeJs is so easy than create a required function like:

function required(moduleName) {
    try {
        return moduleName ? require(moduleName) : undefined;
    } catch (error) {
        // console.log(error);
        //Node red error handle is this ok or need changes?
        node.error("error: " + error.toString(), undefined);
    }
}

thanks for any help, at this point I don't know if this is possible or I'm looking for pink unicorns

Thanks to @knolleary

The solution is:

unsafe-function node for node-red node

unsafe-function node for node-red source

forked version of node-red See stackoverflow answer

You can require npm modules inside the javascript file of each node. Your function should be this way to have the correct boolean value:

function required(moduleName) {
    try {
        require('https').get(`https://www.npmjs.com/package/${moduleName}`,function(response){
  return response.statusCode == 200;

})
    } catch (error) {
        // console.log(error);
        //Node red error handle is this ok or need changes?
        node.error("error: " + error.toString(), undefined);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM