无法读取未定义的属性'emit'(重复)

时间:2016-09-07 10:11:43

标签: node.js websocket

在我目前的项目中,我正在通过 Node.js 从TemperatureSensor读取数据,并通过 web-socket 在浏览器上推送数据。 Node.js代码如下所示:

var http = require('http');
var fs = require('fs');
var port = 8686;
var path = require('path');
var mqtt = require('mqtt');
var sock;
var tempValue,humidityValue,sensorMeasurement;
var client = mqtt.connect('mqtt://test.mosquitto.org');
client.subscribe('sensorMeasurement');

client.on('message', function(topic, payload) {
if (topic.toString() == "sensorMeasurement") {  
sensorMeasurement = JSON.parse(payload);
tempValue=sensorMeasurement.tempValue;
console.log("temperature value : " + tempValue);
sock.emit('sensorData', { value : tempValue });
  }
});


function handleRequest(request, response){
var filePath = path.join(__dirname, 'index.html' );
var stat = fs.statSync(filePath);
response.writeHead(200, {
    'Content-Type': 'text/html',
    'Content-Length': stat.size
});
var readStream = fs.createReadStream(filePath);
readStream.pipe(response);      
}

var server = http.createServer(handleRequest);
var io = require('socket.io').listen(server);
server.listen(port, "0.0.0.0", function(){
console.log("Server listening on: http://localhost:%s", port);
});

io.sockets.on('connection', function (socket) {
sock = socket; 
});

当我在上面运行时,代码显示以下错误:

C:\ABB Work\nodeworkspace\Smart Home App\DataVisualizer.js:18
 sock.emit('sensorData', { value : tempValue });
 TypeError: Cannot read property 'emit' of undefined
 at MqttClient.<anonymous> (C:\ABB Work\nodeworkspace\Smart Home App\DataVisualizer.js:18:7)
at emitThree (events.js:97:13)
at MqttClient.emit (events.js:175:7)
at MqttClient._handlePublish (C:\ABB Work\nodeworkspace\Smart Home App\node_modules\mqtt\lib\client.js:792:12)
at MqttClient._handlePacket (C:\ABB Work\nodeworkspace\Smart Home App\node_modules\mqtt\lib\client.js:282:12)
at process (C:\ABB Work\nodeworkspace\Smart Home App\node_modules\mqtt\lib\client.js:238:12)
at Writable.writable._write (C:\ABB Work\nodeworkspace\Smart Home App\node_modules\mqtt\lib\client.js:248:5)
at doWrite (C:\ABB Work\nodeworkspace\Smart Home App\node_modules\mqtt\node_modules\readable-stream\lib\_stream_writable.js:237:10)
at writeOrBuffer (C:\ABB Work\nodeworkspace\Smart Home App\node_modules\mqtt\node_modules\readable-stream\lib\_stream_writable.js:227:5)
at Writable.write (C:\ABB Work\nodeworkspace\Smart Home App\node_modules\mqtt\node_modules\readable-stream\lib\_stream_writable.js:194:11)

袜子已定义为变量。我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

应使用事件发射器

进行初始化
var EventEmitter = require('events');
var sock = new EventEmitter();