Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 = { ... };?

like image 815
Scott Avatar asked May 21 '14 19:05

Scott


1 Answers

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.

like image 190
Peter Lyons Avatar answered Oct 04 '22 04:10

Peter Lyons