Earth 2 Eddie
Earth 2 Eddie

Reputation: 51

Problems with functions calling other functions in a Node.js library

I'm new to Node.

I moved a bunch of front in functions from my library into a new Node.js library.

I know you have to put it in module.exports = {

and all of the functions have to be of this format: tempToFahrenheit: function(tempInC){

I'm calling the functions from my other script fine but I'm having a problem with the functions calling each other:

tempToFahrenheit: function(tempInC){
    tempInF = (tempInC*1.8)+32;
    return tempInF;
},

getTextWeatherUsingStationUsingRequest: function(theStation){

    const http = require("http");
    const https = require("https");

    // theURL = 'https://api.weather.gov/stations/' + theStation + '/observations/current';
    thePath = '/stations/' + theStation + '/observations/current';


    function requestTheData(){

        var returnedJSON;

        var options = {
          protocol: "https:",
          hostname: "api.weather.gov",
          path: thePath,
          method: "GET",
          headers: {
            'Accept'       : 'application/json',  
            'Content-Type': 'application/json',
            'User-Agent'   : 'MY-TEST-UA'
          }

        };
        var req= https.request(options);

        var theData = '';

        req.on("response", function(res){
            console.log(`STATUS: ${res.statusCode}`);
            console.log(`HEADERS: ${JSON.stringify(res.headers)}`);

            res.on('data', (chunk) => {
              console.log(`BODY: ${chunk}`);
              theData += chunk;
            });

            res.on('end', () => {
                console.log('No more data in response.');                   

                returnedJSON = JSON.parse(theData);
                console.log(returnedJSON.id);

                // Why can't ot find temptoFahrenheit
                theTemp = Math.round( tempToFahrenheit(returnedJSON.properties.temperature.value) )

                windSpeed = Math.round(returnedJSON.properties.windSpeed.value);
                pressure = returnedJSON.properties.barometricPressure.value;

Just above this text you'll see a line trying to call tempToFahrenheit() inside function getTextWeatherUsingStationUsingRequest(). How do I accomplish this? The strange way you have to set up the functions for Node.js (a hash right?) the functions don't seem to have access to each other.

Another more general question. Node.js benefits are supposed to be that you are using Javascript on front and back end and that you can REUSE code, as in libraries. But as we can see here I'm having to make pretty major (and error prone) changes to the code in order for it to work with Node. Also, I'm having to keep two copies of the library, one front end and the other Node. Isn't there a better way to do libraries in Node?

Upvotes: 1

Views: 88

Answers (1)

Kevin
Kevin

Reputation: 81

In a Node library, all of the functions are members of a common object (modules.exports). Therefore, when you want to call one function from another, you must specify that you're calling this.someFunction, not just someFunction (the latter will look for a globally-accessible someFunction, which doesn't exist).

Complicating things a little further, though, if you were to try that in your case, this would refer to the incorrect context, since that call is nested inside a couple asynchronous callbacks (req.on and res.on). You'd therefore have the same problem.

To get resolve this, try adding var self=this; at the beginning of your getTextWeatherUsingStationUsingRequest function, and then change your tempToFahrenheit function call to self.tempToFahrenheit.

(The variable self will propagate correctly through the callbacks through a feature called closure. this doesn't do that because it's a reserved keyword which always refers to the current context.)

Upvotes: 1

Related Questions