var mqtt = require('mqtt'); that shows syntax error

i am following this tutorial regardign saving data to database using mqtt to mysql sensor to mysql via mqtt where i am at the app_mqtt.js part where i try to follow the exact same thing to create the js file but when i try to run it via python, it shows an error of :

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

I have already the mqtt via npm i mqtt and npm install mqtt --save yet it still have such an error, i really need help in this. Thank you.

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 answer

  • answered 2018-11-08 07:47 Sachin Shah

    As per your code , it shows fine.

    1) Try to restart the server.

    2) check your code to this code

    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) At last , re-install the package.

    Note: If still issue , please share your code. So I can debug it.