1

I've seen this code from some tutorials that I've been looking at for Nodejs.

module.exports = router;

I've also looked at this quick post from sitepoint.com about module.exports and I'm a bit confused... why do I see that line at the bottom of some files (not many), while I see code more like that from sitepoint.com in many of the tutorials on Nodejs?

What is the difference, if any?

EDIT: I'm aware of this other SO question. I even looked at it before asking my question. The reason I asked my question is because the other post HAS SO MUCH information on it, its HARD to extract useful information from it when your JUST starting to learn about Nodejs. The 2 answers I received from asking this question clarified MY understanding of WHAT I was asking because there was very little information on the page to understand - IT was more direct and to the point. Not everyone on SO is well versed on Nodejs and all that it does, especially beginners.

While I agree, the 2 questions are very similar in nature. The older question had TOO much information on it, which is I asked my question.

The IMPORTANT thing (at least to me) is now I understand module.exports.

Community
  • 1
  • 1
user3125823
  • 1,846
  • 2
  • 18
  • 46
  • When you `require('filename')`, the `exports` line in 'filename.js' is what is imported. – forgivenson Feb 01 '17 at 18:46
  • 2
    Possible duplicate of [What is the purpose of Node.js module.exports and how do you use it?](http://stackoverflow.com/questions/5311334/what-is-the-purpose-of-node-js-module-exports-and-how-do-you-use-it) – Joe White Feb 01 '17 at 18:55
  • @JoeWhite Really? That question was asked 5 years ago... and this question is different – user3125823 Feb 01 '17 at 18:57

2 Answers2

0

module.exports works together with require() (which you've probably seen at the top of other files) to allow you to import javascript files into other files.

For example, suppose you have a file named MyRoute.js, which ends in module.exports = router;. You want to use that as a route in your application, so in your code where you set up the routes, you add var MyRouteVar = require('path/to/MyRoute')'. Now,MyRouteVaris equal torouterfrom theMyRoute.js` file.

forgivenson
  • 4,394
  • 2
  • 19
  • 28
0

With

module.exports = router;

you are exporting the router variable/object, making it visible throughout the rest of the application.

You can import this in any other file using require:

var router = require('router.js');