最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Run Node.js file on button click event - Stack Overflow

programmeradmin1浏览0评论

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:

The code of TemperatureSensor.js is as below:

    var mqtt = require('mqtt');     
    var client = mqtt.connect('mqtt://test.mosquitto: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 ??

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:

The code of TemperatureSensor.js is as below:

    var mqtt = require('mqtt');     
    var client = mqtt.connect('mqtt://test.mosquitto: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 ??

Share Improve this question asked Mar 18, 2016 at 9:46 Saurabh ChauhanSaurabh Chauhan 3,2213 gold badges23 silver badges47 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

You can't run Node.js code in the browser, they're pletely 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 es 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 plexities of learning to write and maintain REST services, this may well be a better option.

发布评论

评论列表(0)

  1. 暂无评论