Search code examples
javascriptmodulerequirecommonjs

How to use CommonJS exports and imports with SocketIO?


Im trying to modularize my server-side code a little bit with CommonJS Modules. So far this is my module with a function in a motorDriver.jsfile:

var rpio = require('rpio');

function motorDriver() {

    this.makeStep = function(pin) {
        rpio.open(pin, rpio.OUTPUT, rpio.LOW);

        /* On for 1 second */
        rpio.write(pin, rpio.HIGH);
        rpio.sleep(data.interval);

        /* Off for half a second (500ms) */
        rpio.write(pin, rpio.LOW);
    }
  }

  module.exports = motorDriver;

Then I try to import it and use it like so in server.js:

var motorDriver = require('./motorDriver');

io.on('connection', function (socket) {
    var motor = motorDriver()

    socket.on('make step', function () {
        console.log("Make Step");
        motor.makeStep(40)
    });
});

When I trigger this socket with a button press I get the error:

TypeError: Cannot read property 'makeStep' of undefined
    at Socket.<anonymous> (/Users/gov-sur/Documents/CamSlider/server.js:38:15)
    at Socket.emit (events.js:182:13)
    at /Users/gov-sur/Documents/CamSlider/node_modules/socket.io/lib/socket.js:528:12

Anyone knows what I am doing wrong or where my miss understanding is laying?

Thanks in advance!


Solution

  • Insted of exporting the whole module I just exported each function individually:

    function makeStep (pin) {
            rpio.open(pin, rpio.OUTPUT, rpio.LOW);
    
            /* On for 1 second */
            rpio.write(pin, rpio.HIGH);
            rpio.sleep(0.0001);
    
            /* Off for half a second (500ms) */
            rpio.write(pin, rpio.LOW);
        }
    
    module.exports = {
        makeStep
    }
    

    Like this I was able to use it like stated in the initial question but without initializing it as a object:

    var motorDriver = require('./motorDriver');
    
    io.on('connection', function (socket) {
        var motor = motorDriver
    
        socket.on('make step', function () {
            console.log("Make Step");
            motor.makeStep(40)
        });
    });