【问题标题】:var mqtt = require('mqtt'); that shows syntax errorvar mqtt = 需要('mqtt');显示语法错误
【发布时间】:2018-11-09 13:40:26
【问题描述】:

我正在关注本教程,关于使用 mqtt 将数据保存到数据库到 mysql sensor to mysql via mqtt 我在 app_mqtt.js 部分,我尝试按照完全相同的方式创建 js 文件,但是当我尝试运行它时通过python,它显示错误:

File "app_mqtt.js", line 1
var mqtt = require('mqtt'); 
   ^
SyntaxError: invalid syntax

我已经通过npm i mqttnpm install mqtt --save 获得了mqtt,但它仍然有这样的错误,我真的需要帮助。谢谢。

var mqtt = require('mqtt');

var Topic = '#'; //subscribe to all topics

var Broker_URL = 'mqtt://192.168.1.123';

var options = {
    clientId: 'MyMQTT',
    port: 1883,
    keepalive : 60
};

var client  = mqtt.connect(Broker_URL, options);
client.on('connect', mqtt_connect);
client.on('reconnect', mqtt_reconnect);
client.on('error', mqtt_error);
client.on('message', mqtt_messsageReceived);
client.on('close', mqtt_close);

function mqtt_connect()
{
    console.log("Connecting MQTT");
    client.subscribe(Topic, mqtt_subscribe);
}

function mqtt_subscribe(err, granted)
{
    console.log("Subscribed to " + Topic);
    if (err) {console.log(err);}
}

function mqtt_reconnect(err)
{
    console.log("Reconnect MQTT");
    if (err) {console.log(err);}
    client  = mqtt.connect(Broker_URL, options);
}

function mqtt_error(err)
{
    console.log("Error!");
    if (err) {console.log(err);}
}

function after_publish()
{
    //do nothing
}

function mqtt_messsageReceived(topic, message, packet)
{
    console.log('Topic=' +  topic + '  Message=' + message);
}

function mqtt_close()
{
    console.log("Close MQTT");
}

【问题讨论】:

  • 这是 JavaScript,不是 Python...

标签: node.js npm raspberry-pi


【解决方案1】:

根据您的代码,它显示得很好。

1) 尝试重启服务器。

2)检查你的代码到这个代码

npm i mqtt --save

var mqtt = require('mqtt')
var client  = mqtt.connect('mqtt://{Your connection string}')

client.on('connect', function () {
  client.subscribe('presence', function (err) {
    if (!err) {
      client.publish('presence', 'Hello mqtt')
    }
  })
})

client.on('message', function (topic, message) {
 // message is Buffer
 console.log(message.toString())
 client.end()
})

3) 最后,重新安装软件包。

注意:如果仍然有问题,请分享您的代码。所以我可以调试它。

【讨论】:

  • 嗨,我已经尝试通过 npm install reinstall -g 重新启动和重新安装,但它仍然无法正常工作。我将在我的帖子中更新代码
  • @Kelvin 请分享您的完整代码。现在在您当前的代码中没有 var mqtt。 :(
  • 非常抱歉!格式有问题!我已经编辑了,非常感谢您的帮助!
  • @Kelvin 您能否尝试评论您所有的 MQTT 代码,然后输入我的代码并检查您是否仍然收到语法错误?如果没有显示,那么只需在此处设置剩余的代码。
  • @Kelvin 尝试使用sudo npm remove mqtt -g 而不是reinstall 卸载软件包。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-24
  • 1970-01-01
  • 2017-10-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多