我通过这种方式连接到 MQTT:
//mqtt.js
const mqtt = require('mqtt');
var options = {
//needed options
};
var client = mqtt.connect('mqtt://someURL', options);
client.on('connect', () => {
console.log('Connected to MQTT server');
});
我想以这种方式导出客户端对象:
//mqtt.js
module.exports = client;
这样我就可以将它导入到其他文件中并以这种方式使用它:
//anotherFile.js
const client = require('./mqtt');
client.publish(...)
但是,我们都知道这是行不通的!我怎样才能实现这个目标?
更新
我尝试了promise并得到了一个非常奇怪的行为。当我在同一个文件(mqtt.js)中使用 promise (如下面的代码)时,一切正常:
//mqtt.js
const mqtt = require('mqtt');
var mqttPromise = new Promise(function (resolve, reject) {
var options = {
//needed options
};
var client = mqtt.connect('mqtt://someURL', options);
client.on('connect', () => {
client.subscribe('#', (err) => {
if (!err) {
console.log('Connected to MQTT server');
resolve(client);
} else {
console.log('Error: ' + err);
reject(err);
}
});
});
});
mqttPromise.then(function (client) {
//do sth with client
}, function (err) {
console.log('Error: ' + err);
});
但是当我导出 promise 并在另一个文件中使用它时,如下所示:
//mqtt.js
//same code to create the promise
module.exports = mqttPromise;
//anotherFile.js
const mqttPromise = require('./mqtt');
mqttPromise.then(function (client) {
//do sth with client
}, function (err) {
console.log('Error: ' + err);
});
我收到此错误:
TypeError: mqttPromise.then is not a function
最佳答案
您可能可以通过创建 2 个文件来实现您的目标,一个用于处理 mqtt 方法,另一个用于管理连接对象。
这是 mqtt 处理程序的文件:
//mqttHandler.js
const mqtt = require('mqtt');
class MqttHandler {
constructor() {
this.mqttClient = null;
this.host = 'YOUR_HOST';
this.username = 'YOUR_USER';
this.password = 'YOUR_PASSWORD';
}
connect() {
this.mqttClient = mqtt.connect(this.host, {port: 1883});
// Mqtt error calback
this.mqttClient.on('error', (err) => {
console.log(err);
this.mqttClient.end();
});
// Connection callback
this.mqttClient.on('connect', () => {
console.log(`mqtt client connected`);
});
this.mqttClient.on('close', () => {
console.log(`mqtt client disconnected`);
});
}
// // Sends a mqtt message to topic: mytopic
sendMessage(message, topic) {
this.mqttClient.publish(topic, JSON.stringify(message));
}
}
module.exports = MqttHandler;
现在让我们使用导出的模块在另一个文件上创建 mqtt 客户端连接:
//mqttClient.js
var mqttHandler = require('./mqttHandler');
var mqttClient = new mqttHandler();
mqttClient.connect();
module.exports = mqttClient;
通过此导出的模块,您现在可以调用客户端连接对象并使用在另一个文件中的 mqttHandler.js 文件中创建的方法:
//main.js
var mqttClient = require('./mqttClient');
mqttClient.sendMessage('<your_topic>','<message>');
虽然可能有更好的方法来执行您的任务,但这个方法对我来说效果很好......
希望对您有帮助!
关于node.js - 在文件之间共享 mqtt 客户端对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53053147/