We'll load in via a constant variable called geocode the module, and we'll set it equal to require, since we're requiring a local file we'll add that relative path, ./geocode/geocode.js:
const geocode = require('./geocode/geocode.js');
That means you need to make a directory called geocode in the weather-app folder, and a file called geocode.js. Since we have a .js extension, we can actually leave it off of our require call.
Now, in the app.js file, next to .argv object, we need to call geocode.geocodeAddress. The geocodeAddress function, that will be the function responsible for all the logic we currently have in app.js. The geocodeAddress function will take the address, argv.address:
geocode.geocodeAddress(argv.address);
It will be responsible for doing everything, encoding the URL, making the request, and handling all of the error cases. This means, in that new file we need to export the geocodeAddress function, just like we exported functions from the notes application file. Next, we have all of the logic here:
var encodedAddress = encodedURIComponent(argv.address);
request({
url: `https://maps.googleapis.com/maps/api/geocode/json?address=${encodedAddress}`,
json: true
}, (error, response, body) => {
if (error) {
console.log('Unable to connect Google servers.');
} else if (body.status === 'ZERO_RESULTS') {
console.log('Unable to find that address.');
} else if (body.status === 'OK') {
console.log(`Address: ${body.results[0].formatted_address}`);
console.log(`Latitude: ${body.results[0].geometry.location.lat}`);
console.log(`Longitude: ${body.results[0].geometry.location.lng}`);
}
});
This logic needs to get moved inside of the geocodeAddress function. Now we can copy and paste the preceding shown code directly, there really is no way around some of the more complex logic, but we will need to make a few changes. We'll need to load requests into that new file, since we use it and it isn't going to be required in that file by default. Then we can go ahead and clean up the request require call in the code, since we won't be using it in this file.
Next up, the argv object is not going to exist, we'll get that passed in via the first argument, just like the argv.address in the geocode.Address statement. This means we'll need to swap this out for whatever we call that first argument for example, address. Once this is done, the program should work exactly as it works without any changes in app.js, there should be no change in functionality.