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 = { ... };
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With