var mqtt = require('mqtt');显示语法错误

时间:2018-11-08 06:38:25

标签: node.js npm raspberry-pi

我正在按照本教程使用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");
}

1 个答案:

答案 0 :(得分:0)

根据您的代码,它可以正常显示。

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)最后,重新安装软件包。

注意:如果仍然发出,请共享您的代码。所以我可以调试它。