【发布时间】:2019-04-02 20:04:18
【问题描述】:
我通过这种方式连接到 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');
});
我想以这种方式导出 client 对象:
//mqtt.js
module.exports = client;
这样我就可以将它导入其他文件并以这种方式使用它:
//anotherFile.js
const client = require('./mqtt');
client.publish(...)
但是,我们都知道这是行不通的!我怎样才能做到这一点?
更新
我尝试了 promise 并得到了一个非常奇怪的行为。当我像下面的代码一样在同一个文件(mqtt.js)中使用承诺时,一切正常:
//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);
});
但是当我导出承诺并在另一个文件中使用它时,像这样:
//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 不是函数
【问题讨论】:
标签: node.js export mqtt node-modules