How to use "require" in a module?



  • I’m trying to make my first module. A pretty simple one, I just want to display the IP address of my Raspberry Pi. (I’m not assigning it a static addr, so if it changes I’d like to know the new addr to remote into)

    A quick google turned up some code for querying for your local IP address. However, it’s not working. I’m getting “Uncaught ReferenceError: require is not defined”. Am I missing something silly here? (Yes, I know the actual ip-getting code is commented out, I’ll bring it back once I can get the reference to os working)

    Here’s the code:

    var os = require("os");
    Module.register("my_ip", {
    
        // Default module config.
    	defaults: {
    	},
    
        // Override dom generator.
    	getDom: function () {
    	    var ip = location.host;
    
    	    /*
    	    var ifaces = os.networkInterfaces();
    
    	    Object.keys(ifaces).forEach(function (ifname) {
    	        var alias = 0;
    
    	        ifaces[ifname].forEach(function (iface) {
    	            if ('IPv4' !== iface.family || iface.internal !== false) {
    	                // skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
    	                return;
    	            }
    
    	            if (alias >= 1) {
    	                // this single interface has multiple ipv4 addresses
    	                console.log(ifname + ':' + alias, iface.address);
                        ip = iface.address;
    	            } else {
    	                // this interface has only one ipv4 adress
    	                console.log(ifname, iface.address);
                        ip = iface.address;
    	            }
    	            ++alias;
    	        });
    	    });
            */
    
    	    var wrapper = document.createElement("div");
    	    wrapper.innerHTML = ip;
    		return wrapper;
    	},
    
    });
    


  • take a look into the documentation on how to write a module, especially the part with node_helper



  • Thanks! I’ve got it working with node_helper now. It seems a bit convoluted though, since my module now sends a socket notification to request the IP, and listens for the socket notification to refresh the local variable and redraw the DOM. Is this actually the correct way to do it?


  • Moderator

    That’s how the node_helper method works, module sends a request, the node_helper.js script responds.


Log in to reply
 

Looks like your connection to MagicMirror Forum was lost, please wait while we try to reconnect.