Why should the module be declared at the bottom of the file?

I have the following 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 fire node and say that the required object does not have a read or write method. Whether the variable lifting force will perform functions above modules.export = { ... }; ?

+8
hoisting
source share
1 answer

This is the syntax you use to declare functions that are important because of the hoisting function . If you declare these functions as follows, they will be โ€œraisedโ€ in scope and everything will be fine.

 module.exports = { read: read, write: write, }; function read(parameters, config, next) { /* <snip> */ }; function write(parameters, config, next) { /* <snip> */ }; 

Side note. Named functions like my fragment, unlike anonymous functions assigned to variables like in your fragment, itโ€™s easier to debug the profile, because their name falls into the stack traces.

+14
source share

All Articles