0

I am working on a node_module where I want to force users to pass in a string argument during require, like this:

const module = require('mymodule')('argument')

Then I have this on the module:

var someName = ''
module.exports = function (name) {
  if (!name) console.log('Error!')
  someName = name
  console.log('Set someName: ' + someName)
}

So this works fine. However, when I try to require like this:

const module = require('mymodule')

And I added this:

module.exports = () => {
  throw new Error('No name defined')
}

It doesn't go in there and no error is thrown.

How can I force users so that they will pass in an argument during require?

Thanks!

kzaiwo
  • 1,558
  • 1
  • 16
  • 45
  • What does your mymodule export? – Ravi Kukreja Jul 07 '20 at 03:19
  • `require('mymodule')` would still return your function. Having `require('mymodule')('argument')` is the same as `const mymodule = require('mymodule'); mymodule('argument')`. Naming your variable `module` in a Node module is probably a very bad idea – Phil Jul 07 '20 at 03:19
  • mymodule exports multiple functions.. Basically, I just want to force user to pass in a string argument before using the other exported functions. Something like a constructor but for node_module. Is this possible? – kzaiwo Jul 07 '20 at 03:21
  • If you use `module.exports = function(...`, you can only export a single function. See [Declare multiple module.exports in Node.js](https://stackoverflow.com/questions/16631064/declare-multiple-module-exports-in-node-js) – Phil Jul 07 '20 at 03:29

1 Answers1

0

Based on your comment responses, you mention that you want a constructor for your module exports. There's no reason it can't just return a class that requires a constructor, or a function that returns such a class.

class c {

    constructor(name) {
        if (name === undefined)
            throw 'please pass a name';
        this.name = name;
    }

    // other stuff

}

module.exports = name => new c(name);
pwilcox
  • 5,542
  • 1
  • 19
  • 31