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

polentz
polentz
Full Stack JavaScript Techdegree Student 11,647 Points

module.exports and require clarification

So when the instructor does module.exports.get = get is the same as module.exports = get and then in the file that we require it we do const get = require("./profile")?

1 Answer

Michael Hulet
MOD
Michael Hulet
Treehouse Moderator 47,033 Points

Setting get to be exported like this:

profile.js
module.exports.get = get;

will make it so that whenever another file requires this one, they'll have to call .get on the object they're importing to access the get function, like this:

const profile = require("./profile.js");

profile.get();

However, setting module.exports to be get directly like this:

profile.js
module.exports = get;

will cause the object that require returns to just be the get function itself, so whenever another file requires this one, they'd use the get function like this:

const get = require("./profile.js");

get();