Bun
Bun

Reputation: 3137

What does this line in NodeJs mean?

I'm wondering what does these require lines in NodeJs mean.

 var debug = require('debug')('morgan')
 var deprecate = require('depd')('morgan')

I'm going through the index.js of morgan package in NodeJs. Normally require only has one parameter (package).

Upvotes: 1

Views: 72

Answers (1)

Sukima
Sukima

Reputation: 10084

require returns what ever was defined in the package. In the cases above they are functions and so the second parameter is actually calling the function. If you break it out it would look like this:

var debugFunctionFactory = require('debug');
var debug = debugFunctionFactory('morgan');
debug('this is a test debug command');

The implementation is easy if the module in question returns a function. And in the case of debug and deprecate it returns a function that returns a function:

// Module code:
module.export = function(customName) {
  return function(message) {
    console.log(customName + ': ' + message);
  };
};

// Your code:
var foo = require('module'); // => function
var bar = foo('foobar');     // => function
bar('baz');                  // "foobar: baz"

// More concisely:
var foo = require('module')('foobar');  // => function
foo('baz');                             // "foobar: baz"

Upvotes: 2

Related Questions