JavaScript Node.js Basics Handling Errors in Node Organizing Your Code with require

Brian Patterson
Brian Patterson
19,584 Points

node not responding.

Me again. Sorry being really thick here. Or is Andrew explaining this really badly? I am trying have tried to separate the code into two files. Here is my season.js code.

const http = require('http');

//Print Error Messages
function printError(error) {
  console.error(error.message);
}

//Function to print message to console
// function printMessage(username, badgeCount, points) {
//   const message = `${username} has ${badgeCount} total badge(s) and ${points} points in JavaScript`;
//   console.log(message);
// }
function printMessage(races, season) {
  const message = `There are ${season} grandprix at the ${races} season.`;
  console.log(message);
}

function get(season) {
  try {
    // Connect to the API URL (https://teamtreehouse.com/username.json)
    const request = http.get(
      `http://ergast.com/api/f1/${season}.json`,
      response => {
        if (response.statusCode === 200) {
          let body = '';
          // Read the data
          response.on('data', data => {
            body += data.toString();
          });

          response.on('end', () => {
            try {
              // Parse the data
              const seasonF1 = JSON.parse(body);
              // Print the data
              printMessage(season, seasonF1.MRData.RaceTable.Races.length);
            } catch (error) {
              printError(error);
            }
          });
        } else {
          const message = `There was an error getting the profile for ${season} (${
            http.STATUS_CODES[response.statusCode]
          })`;
          const statusCodeError = new Error(message);
          printError(statusCodeError);
        }
      }
    );
    request.on('error', printError);
  } catch (error) {
    printError(error);
  }
}

module.exports.get = get;

And here is my seasonF1.js file.

const season = require('./season.js');

const seasons = process.argv.slice(2);
seasons.forEach(season.get);

When I run node season.js it returns nothing.

Also, I don't understand about the module.exports.get = get; He does a great job of explaining this badly.

Brian Patterson
Brian Patterson
19,584 Points

Just worked it out. I did not add a year at the end. But I still don't understand about the exports.

1 Answer

Jennifer Nordell
MOD
Jennifer Nordell
Treehouse Moderator

Hi there, Brian! I'm glad you got it partially worked out. As for the module.exports.get = get part. I can try and explain it briefly. You have a function in the first file named get. And we want our other file to be able to use that function. So we export it in a module. That and we export it as the same name ... get. And there's a reason we do this: to avoid collisions. Imagine for a moment potentially how many frameworks out there have a get function. Probably hundreds or more.

There is a workshop on this very thing at Treehouse. It's about 16 minutes long and will likely clear this up for you entirely. I recommend you take a look at this workshop

Hope this helps! :sparkles:

Brian Patterson
Brian Patterson
19,584 Points

Thanks Jennifer for the reply. It sort of makes sense. As I understand it you want to export the function get to the seasonF1.js file. So we do this in a module. Now the ...get is where I am confused. If a function was named

function foo() {
}

Do we write module.exports.foo = foo; ?
Like Andrew, Huston does not explain this very well. Or maybe I'm very thick and don't understand this.

Jennifer Nordell
Jennifer Nordell
Treehouse Moderator

Right. The thing on the left side is what we'll call the function when it's in the other file. We're exporting with the name get. The thing on the right side is what it's called in this file.

So for your example, we could do this:

function foo() {
}

module.exports.bar = foo;

But if we did that then that would mean that the function would be accessed as bar in the file where it was required. Does that make sense?

Brian Patterson
Brian Patterson
19,584 Points

Thanks Jennifer for your reply. I understand now. The mini challenge after the video explained it properly for me. Maybe going forward a better way to explain this concept is for the module.exports is different from the function your calling. It's unfortunate that both sides are named

get

I just think this could have been explained better.

Jennifer Nordell
Jennifer Nordell
Treehouse Moderator

Brian Patterson you could be right. Might I suggest that you send that as a suggestion to Treehouse staff? In my experience, Treehouse loves to get feedback from their students. You can reach them and leave suggestions at help@teamtreehouse.com.

To be clear, I am not employed by Treehouse. I'm a student just like you! :sparkles:

Brian Patterson
Brian Patterson
19,584 Points

Well, I am impressed by your knowledge. I will provide the feedback. Just a quick question. I am probably not the only that has said this. I do struggle with software development, but I find it very hard to let it go. I would be interested in how you learn the different concepts. Thanks for taking the time to reply to my ramblings!

Jennifer Nordell
Jennifer Nordell
Treehouse Moderator

Brian Patterson ... honestly? Sheer persistence. Some concepts are just naturally more difficult and more abstract than others. That's pretty true for just about any subject matter.

I actually wrote a blog post related to this topic a while ago. Check it out if you have time :smiley: