如何在SocketIO中使用CommonJS导出和导入?

时间:2019-05-05 10:28:33

标签: javascript module require commonjs

我正在尝试使用CommonJS模块将我的服务器端代码模块化。到目前为止,这是我的模块,在motorDriver.js文件中具有函数:

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;

然后我尝试将其导入并像在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)
    });
});

当我按下按钮触发此套接字时,出现错误:

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

任何人都知道我在做错什么,或者我的错过理解在哪里?

谢谢!

1 个答案:

答案 0 :(得分:0)

要导出整个模块,我只是单独导出了每个函数:

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
}

像这样,我能够像初始问题中所述使用它,而无需将其初始化为对象:

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

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

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