-1

In my current project, we have a HTML page. In HTML page, we have several buttons, for instance we have buttons for Temperature Sensor, Humidity Sensor, Alarm etc. When we click on a button than in back-end it will run corresponding Node.js file, for instance when we click on Temperature sensor button than it will run TemperatureSensor.js file located in the same path. The code for HTML page is as shown below: View of HTML page

The code of TemperatureSensor.js is as below:

    var mqtt = require('mqtt');     
    var client = mqtt.connect('mqtt://test.mosquitto.org:1883'); 
    var NUM_SAMPLE_FOR_AVG = 5;
    var numSample = 0;      
    var tempCelcius = 0;        
    var currentAvg = 0;     
    client.subscribe('tempMeasurement');
    client.on('message', function(topic, payload) {     
        if (topic.toString() == "tempMeasurement") {
            sensorMeasurement = JSON.parse(payload);
            console.log("tempValue is " + sensorMeasurement.tempValue);
            if (numSample <= NUM_SAMPLE_FOR_AVG) {      
                numSample = numSample + 1;      
                if (sensorMeasurement.unitOfMeasurement == 'F') {       
                    tempCelcius = ((sensorMeasurement.tempValue - 32) * (5 / 9));       
                } else {        
                    tempCelcius = sensorMeasurement.tempValue;      
                }       
                currentAvg = parseFloat(currentAvg) + parseFloat(tempCelcius);      
                if (numSample == NUM_SAMPLE_FOR_AVG) {      
                    currentAvg = currentAvg / NUM_SAMPLE_FOR_AVG;       
                    var avgTemp = {     
                        "tempValue" : parseFloat(currentAvg),       
                        "unitOfMeasurement" : sensorMeasurement.unitOfMeasurement       
                    };      
                    client.publish('roomAvgTempMeasurement', JSON
                            .stringify(avgTemp));       
                    console.log("Publishing Data roomAvgTempMeasurement "); 
                    numSample = 0;  
                    currentAvg = 0;     
                }       
            }
                } 

    }); 

The problem is when we clicked on TemperatureSensor button in browser than it display error: TemperatureSensor.js:1 Uncaught ReferenceError: require is not defined. if the content of TemeperatureSensor is console.log("Hello") than it displays Hello in the console of browser. How to provide dependency ??Why we need to do this bcoz if we want to run TemperatureSensor, HumiditySensor etc. than we need to run these in terminal, for instance if we want to run TemperatureSensor than in terminal we have to write sudo node TempeatureSensor.js. This require more manual efforts so in order to reduce this effort we need such kind of HTML page. How to resolve the about problem ??

Saurabh Chauhan
  • 3,161
  • 2
  • 19
  • 46

1 Answers1

4

You can't run Node.js code in the browser, they're completely separate environments (for example, browsers do not have the require function, hence why you're getting that error). Your best bet is to look into creating a REST service of some kind (using Express, Hapi or Restify, most likely) that will allow you to call a Node.js server through HTTP.

This is a decent introduction to the topic - it uses MongoDB for data persistence, but this is in no way a requirement when it comes to making stuff like this. In your case, you'll basically just have to define a route for Temp and Humidity, run your code to get the data in the route handler, and then send JSON data back on the response object. You'll then be able to use jQuery (or any number of other libraries) to make AJAX requests to these routes.

EDIT: After looking at the MQTT GitHub page, there is another option - the library can be used in the browser if bundled using a tool like Browserify or Webpack. Given the complexities of learning to write and maintain REST services, this may well be a better option.

Joe Clay
  • 33,401
  • 4
  • 85
  • 85
  • I am able to run Node.js file with content console.log("Hello"); and in this case it display Hello to console of the browser. Could please provide more information with some example ?? It would be grateful for me. – Saurabh Chauhan Mar 18 '16 at 09:52
  • @Saurabh13: [This is a decent introduction to the topic](https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4) - it uses MongoDB for data persistence, but this is in no way a requirement when it comes to making stuff like this. In your case, you'll basically just have to define a route for `Temp` and `Humidity`, run your code to get the data in the route handler, and then send JSON data back on the response object. You'll then be able to use [jQuery](http://api.jquery.com/jquery.ajax/) (or any number of other libraries) to make AJAX requests to these routes. – Joe Clay Mar 18 '16 at 09:57
  • @Saurabh13: There's nothing about `console.log` which is specific to Node, it's just normal JavaScript, so your browser can run that fine. It's when you start trying to import packages that things start to differ. – Joe Clay Mar 18 '16 at 10:02
  • Thank you for the information. Actually I am not much clear. Can I use jQuery to make AJAX requests to Node.js file ?? – Saurabh Chauhan Mar 18 '16 at 10:05
  • 1
    @Saurabh13: You can use jQuery to make AJAX requests to any REST service, it's not specific to Node. Express will allow you to create a Node.js file that will run a server and can respond to these AJAX requests. – Joe Clay Mar 18 '16 at 10:09
  • Can I follow http://stackoverflow.com/questions/19059580/client-on-node-uncaught-referenceerror-require-is-not-defined post answer ?? Specially browserify ??? – Saurabh Chauhan Mar 18 '16 at 10:12
  • @Saurabh13: Ah, actually, there is a section on the MQTT GitHub page about using Browserify, so that might be easier. https://github.com/mqttjs/MQTT.js#browserify – Joe Clay Mar 18 '16 at 10:22
  • Thank you for the pointer. I know MQTT add more complexity in our this task. – Saurabh Chauhan Mar 18 '16 at 10:30
  • @Saurabh13: After taking a closer look at it, I think Browserify is probably your best option, it'll save you a fair bit of complexity. – Joe Clay Mar 18 '16 at 10:32
  • I am agree but I think I have to do more engineering task, because in this case browser contact Node.js file using web socket than it connect with MQTT client. Am I right ?? – Saurabh Chauhan Mar 18 '16 at 10:39
  • Could you please add your current comment as post so that it will be helpful to other also as it is close approach. – Saurabh Chauhan Mar 18 '16 at 10:41
  • @Saurabh13 - You should be able to use the library through Browserify and have your web browser connect directly to MQTT without having to have your own Websockets server. I've never used MQTT though, so this is just speculation! And yes, I'll edit my post. – Joe Clay Mar 18 '16 at 10:44