Scott
Scott

Reputation: 6736

Why must a module's exports be declared at the bottom of a file?

I have the following redacted code:

module.exports = {
  read: read,
  write: write,
};

var read = function(parameters, config, next) {
  /* <snip> */
};

var write = function(parameters, config, next) {
  /* <snip> */
};

If I go to require() this file elsewhere, it will crash node and say that the required object has no method read or write. Wouldn't variable hoisting pull the functions above the modules.export = { ... };?

Upvotes: 14

Views: 5288

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 146084

It's the syntax you use to declare functions that matters due to function hoisting. If you declare those functions like this, they will get "hoisted" up in the scope and all is well.

module.exports = {
  read: read,
  write: write,
};

function read(parameters, config, next) {
  /* <snip> */
};

function write(parameters, config, next) {
  /* <snip> */
};

Side note: Named functions like in my snippet, as opposed to anonymous functions assigned to variables like in your snippet, are easier to debug and profile because their name gets included in stack traces.

Upvotes: 21

Related Questions