-2

Referencing this solution, I need to pass a parameter into module.exports of my utils.js file.

// utils.js
var module;
module.exports = function (name) {
    if (module) return module;

    module = {};

    module.sayHi = function () {
        return `Hi, ${name}`;
    };

    return module;
};

I'm a bit confused as to how to call sayHi after requireing utils.js.

// index.js
const utils = require("./utils")("Jim");    
utils.sayHi();

I'm getting TypeError: utils.sayHi is not a function. What's the right way to call sayHi?

slider
  • 2,736
  • 4
  • 33
  • 69

1 Answers1

0

First you create a variable named module.

var module;

This does nothing because you are doing this in the scope of the module, so that variable already exists.


Then you assign a function to module.exports.

In another module, you import that function and call it.

The first line of that function says:

if (module) return module;

Is module a truthy value?

Yes. It is an object. If it wasn't, then assigning to module.exports would have throw an exception.

Consequently, you never overwrite module = {}; or assign the sayHi function to it.


Now look at the answer you referenced:

module.exports = function (app, db) {
    var module = {};

It creates a new variable in the scope of the function so it doesn't conflict with the existing one.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • The reason for `var module;` outside of the `module.exports` scope was to attempt caching of the module if referenced multiple times (see: https://stackoverflow.com/questions/13151693/passing-arguments-to-require-when-loading-module/13163075#comment82835819_13163075). I could have a value in the module not worth recomputing multiple times. It's just that my current implementation doesn't seem to work. – slider Sep 20 '20 at 19:14
  • @slider — As implied by the answer, you could just *use a different variable name* … but then it would cache the first name you passed to the `name` argument and you'd be stuck with it for subsequent invocations. If you want to cache sanely, you'd need to store the result from each `name` separately. – Quentin Sep 20 '20 at 19:20
  • @slider But you don't want caching, if the exported function is called with different `name`s. – Bergi Sep 20 '20 at 19:23
  • In this case, yes, `name` would be a bad parameter for something worth caching. But other values may indeed be worth caching. – slider Sep 20 '20 at 19:25