Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How does this work?

So In the node.js basics Q/Ans. I found this -

Given the following code in greeting.js:

function sayGreeting() {
  console.log("Hello World");
}

module.exports.say = sayGreeting;

How would you access the functionality from another file?

Now I figured out the answer. It's option A:

A )    const greeting = require("./greeting");
greeting.say();

B )     const greeting = require("./greeting");
greeting.sayGreeting();

Now, how come the 1st one works and the second one doesn't? I don't get it.

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! The key lies in this line:

module.exports.say = sayGreeting;

It was exported as say. Now we could've picked any valid JavaScript variable here, but we picked one that made sense. When I first saw the require statement I thought it was pulling in the entire file that was being required, but I was wrong. I'm wondering if this is what you thought, too. It turns out that what is returned by the require are the modules that are exported. Here, the module being exported is named say.

Hope this helps! :sparkles:

Oh, thank you, Jennifer Nordell. You are a lifesaver. This one had got me bugged for a while.