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

Why is he exporting only a part of the code?

There is something that I am missing that makes me feel confused about export. We are exporting a part of the code but how the script is supposed to work without all of it? I understood something wrong if someone could clarify it would be amazing!

Thanks, Stavros

2 Answers

Michael Liendo
Michael Liendo
15,323 Points

Solid question!

module.export.anyFunctionName 

will export that function, but also anything within the file that the function needs to work (dependencies, other function etc.)

Thank you very much

In real world settings this allows you to have that file only expose certain methods to end users. This allows you to modify the existing code easier by knowing what the user is directly accessing and what is not being directly accessed.

For example if you have 3 methods in your js file and expose only 1 then you as the developer are free to change the 2 that are not exposed without as much worry about breaking the code.

If you had a project that relied on say the

const module = require('./modulefile.js');

//super important function that has to work
module.superImportantFunction();

than if you wanted to optimize or update modulefile.js you just have to make sure that you expose that method

module.export.superImportantFunction = MyFunction;

This allows you to update one of your "modules" and helping it play nicely in your full program.