在我目前的项目中,我正在通过Node.js读取温度传感器的数据,并通过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 WorknodeworkspaceSmart Home AppDataVisualizer.js:18
sock.emit('sensorData', { value : tempValue });
TypeError: Cannot read property 'emit' of undefined
at MqttClient.<anonymous> (C:ABB WorknodeworkspaceSmart Home AppDataVisualizer.js:18:7)
at emitThree (events.js:97:13)
at MqttClient.emit (events.js:175:7)
at MqttClient._handlePublish (C:ABB WorknodeworkspaceSmart Home Appnode_modulesmqttlibclient.js:792:12)
at MqttClient._handlePacket (C:ABB WorknodeworkspaceSmart Home Appnode_modulesmqttlibclient.js:282:12)
at process (C:ABB WorknodeworkspaceSmart Home Appnode_modulesmqttlibclient.js:238:12)
at Writable.writable._write (C:ABB WorknodeworkspaceSmart Home Appnode_modulesmqttlibclient.js:248:5)
at doWrite (C:ABB WorknodeworkspaceSmart Home Appnode_modulesmqttnode_modulesreadable-streamlib_stream_writable.js:237:10)
at writeOrBuffer (C:ABB WorknodeworkspaceSmart Home Appnode_modulesmqttnode_modulesreadable-streamlib_stream_writable.js:227:5)
at Writable.write (C:ABB WorknodeworkspaceSmart Home Appnode_modulesmqttnode_modulesreadable-streamlib_stream_writable.js:194:11)
sock已经定义为变量。我错过什么了吗?
应该用事件Emitter
进行初始化var EventEmitter = require('events');
var sock = new EventEmitter();