Search code examples
javascriptnode.jsrequirejsminimist

What's the JavaScript syntax after the require() call?


The following code is from the Node.js course I am following:

var args = require("minimist")(process.argv.slice(2), { string: "name"});

I understand that a module is being imported, but I don't understand the second set of parentheses after the require() call:

require("minimist")(this part I don't understand)

Specifically, what is the second set of parentheses in terms of syntax?

I know how slice() works, and I understand that string: "name" creates a command line argument to check for, but what method is being called through the require() call, and how?

PS: The course (by Kyle Simpson) indicates that the above syntax will be explained later, but I haven't been able to locate the specific part, and I don't like to proceed without understanding something. I am new to both JS and Node.js.


Solution

  • In this case it looks like the module you are requiring is simply returning a function which you are immediately calling with () and passing in two arguments: process.argv.slice(2) and { string: "name"}

    So if your module looked like this:

    // minimist.js
    function test(str){
        console.log(str)
        return "Called with:" + str
    }
    module.exports = test;  // exports the function
    

    you could use it like:

    var arg = require('./minimist.js')("Hello") // calls the function minimist.js exported