我有代码:
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."
我做错了什么?
答案 0 :(得分:2)
您正在发出“错误”事件,但正在捕捉“错误”事件。
serialConnector.on('err',function(err){ //<-- Should be 'error'
console.log('Test');
console.log(err);
});