我已经很好地补充了MQTT,但是我遇到execute()
方法的问题。除此之外,所有其他功能(unsubscribe
)都可以正常工作。我已经检查了拼写,甚至完成了mqttCon.publish() , mqttCon.subscribe(), mqttCon.on()...
,并将其带到库实现中,这意味着它是正确的方法,并得到了很好的引用,但我仍然在下面得到错误。我该怎么解决?
此行: ctrl +click
mqttCon.unsubscribe(topic)
注意:我正在使用ES6(Emacscript 6+)javascript和不是打字稿。
Nodejs TypeError: mqttCon.unsubscribe is not a function
at noopHandler (/home/dev/project-dir/src/mqtt/processMessage.js:5:13)
at module.exports (/home/dev/project-dir/src/mqtt/processMessage.js:10:20)
at MqttClient.client.on (/home/dev/project-dir/src/mqtt/mqttCon.js:16:13)
at MqttClient.emit (events.js:189:13)
at MqttClient._handlePublish (/home/dev/project-dir/node_modules/mqtt/lib/client.js:1271:12)
at MqttClient._handlePacket (/home/dev/project-dir/node_modules/mqtt/lib/client.js:410:12)
at work (/home/dev/project-dir/node_modules/mqtt/lib/client.js:321:12)
at Writable.writable._write (/home/dev/project-dir/node_modules/mqtt/lib/client.js:335:5)
at doWrite (/home/dev/project-dir/node_modules/mqtt/node_modules/readable-stream/lib/_stream_writable.js:428:64)
at writeOrBuffer (/home/dev/project-dir/node_modules/mqtt/node_modules/readable-stream/lib/_stream_writable.js:417:5)
和npm 12.18.1
这是我的连接代码6.14.6
:
mqttCon.js
这是const mqtt = require('mqtt')
const processMessage = require('./processMessage')
const logger = require('../logConf')
const options = {
host: '',
port: '',
username:'',
password: '',
protocol: ''
};
const client = mqtt.connect(options)
client.on("connect", function () {
console.log("MQTT connected with status: " + client.connected);
if (client.connected) {
client.on('message', (topic, message) => {
processMessage(topic, String(message))
})
}
})
client.on('error', error => {
console.log(error,'ERROR')
logger.errorLogger.error(error)
})
client.on('reconnect', error => {
console.log(error,'RECONNECT')
logger.errorLogger.error(error)
})
client.on('close', error => {
console.log(error,'CLOSE')
logger.errorLogger.error(error)
})
client.on('disconnect', error => {
console.log(error,'DISCONNECT')
logger.errorLogger.error(error)
})
client.on('offline', error => {
console.log(error,'OFFLINE')
logger.errorLogger.error(error)
})
module.exports = client
:
processMessage.js
答案 0 :(得分:1)
您的mqttCon.js文件没有client.prototype.unsubscribe = function() {}
,因此错误是正确的。您正在将client
定义为模块,但是实际上您需要在某个地方调用mqtt.unsubscribe()
。因此,您需要在unsubscribe()
常量中添加client
函数(在这种情况下,它实际上应该是var
),或者在需要mqtt之后调用mqtt.unsubscribe()
函数您的processMessage.js文件中的模块...。我认为这与您尝试执行的操作背道而驰。您可能需要阅读更多有关module.exports实际工作原理的信息:https://www.sitepoint.com/understanding-module-exports-exports-node-js/
更新:
上面的内容影响了我的想法,问题是我正在导入processMessage.js
,而这反过来又导入了导入mqttCon.js
。循环导入,意味着mqttCon
(mqttClient)始终尚未在processMessage.js
内部初始化。解决方案是,当客户端已经初始化并导出为以下模块时,我将processMessage.js
导入了client.on('connect'....)...
块中:
client.on("connect", () => {
console.log("MQTT connected with status: " + client.connected);
if (client.connected) {
client.on('message', (topic, message) => {
require('./processMessage')(topic, String(message))
})
}
})