JavaScript Node.js Basics Create a Command Line Weather Application Retrieving Data - Solution

Jarren Bird
Jarren Bird
8,118 Points

why don't i have to require my weather.js file in app.js?

in this project, andrew has an app.js file, a weather.js file, and an api.json file. the weather.js file has a function that app.js uses. so it would make sense that the app.js file has to require the weather.js file in order to get that function. and this is the way that andrew has it set up in his video.

but when i require the weather.js file in app.js, like this:

const weather = require('./weather');

i get an error. the error i get is:

"Identifier 'weather' has already been declared"

if i remove that line, then everything seems to work like it's supposed to.

so my question is: why does andrew have to require weather.js and i don't?

Jesus Mendoza
Jesus Mendoza
23,270 Points

Hey Jarren,

I guess thats happening because you already defined a variable called 'wather'. Post the rest of your code so I can take a look!

Jarren Bird
Jarren Bird
8,118 Points

thanks for the reply! that's what i thought too, but i wasn't seeing it anywhere. either way it'd be good to get fresh eyes on it.

app.js:

// require my weather function
 const weather = require('./weather');
// i don't know why i don't have to require this file, but it works when i don't require it
// and it doesn't work when i do require it

// join values passed as arguments and replace all spaces with underscores
const query = process.argv.slice(2).join('_').replace(' ', '_');
// example queries
// query: 90210
// query: Cleveland_OH
// query: London_England
weather.get(query);

weather.js:

// require node https module
const https = require('https');

// require my API module
const api = require('./api.json');

function get(query) {
    // connect to the API URL (https://api.wunderground.com/api/${api.key}/geolookup/conditions/q/${query}.json)
    const request = https.get(`https://api.wunderground.com/api/${api.key}/geolookup/conditions/q/${query}.json`, response => {
        // the chunks of data will be parsed and added to this sexy variable
        let body = "";
        // read the data
        response.on('data', chunk => {
            body += chunk;
        });
        response.on('end', () => {
            console.log(body);
            // parse the data
            // print the data
        });
    });
}

module.exports.get = get;

// todo: handle errors

and there's one more file that i didn't mention, but i'll put it here just to be complete.

api.json:

{
    "key": "63999003ac6ecf54"
}

Hi Jarren, did you find the mistake ? I ran your code on my computer (with my own API-key) and it works as expected: fine with requiring the weather-module and not without it .