0

我有代码:

    var events = require('events');

    var serialport = require("serialport");
    var SerialPort = serialport.SerialPort;
    var serialPort;


    function SerialConnector(){

    //EventEmitter constructor
    events.EventEmitter.call(this);

    var self = this;

    this.connect = function (pathToSerialPort, options)
        {

            serialPort = new SerialPort(pathToSerialPort, options, false);

            serialPort.open();

            serialPort.on('open', function(data){

                self.emit('open', data);
            });

            serialPort.on('close', function(err){

                self.emit('close', err);
            });

            serialPort.on('error', function(err){

                self.emit('error', err);
            });

            serialPort.on('data', function(data){

                self.emit('data', data);
            });
        };  

    }

//Copies all of the EventEmitter properties to the SerialConnector object

SerialConnector.prototype.__proto__ = events.EventEmitter.prototype;

module.exports = SerialConnector;

我需要另一个文件中的模块并像这样调用它:

var SerialConnector = require('./serial.connector.js');

var serialConnector = new SerialConnector();

serialConnector.on('err',function(err){
    console.log('Test');
    console.log(err);
});

serialConnector.connect("/dev/ttyUSB0",{
    baudrate : 19200,
    dataBits : 8,
    parity : 'none',
    stopBits : 1
});

发出串行端口事件时,它会抛出

"event.js:2877: Uncaught TypeError: Uncaught, unspecified "error" event." 

我究竟做错了什么?

4

1 回答 1

2

您正在发出“错误”事件,但正在捕获“错误”事件。

serialConnector.on('err',function(err){ //<-- Should be 'error'
    console.log('Test');
    console.log(err);
});
于 2013-11-27T08:46:12.463 回答