如何在NodeJS中要求带有和不带有参数的模块?

问题描述 投票:0回答:2

我的查询:

如何区分所需的模块中是否包含参数?

详细信息:

我已经编写了一个模块,该模块将用彩色控制台消息(作为参数传递)。如果没有通过,则选择默认颜色(例如白色)。

require('my-module');    //should print 'Hello World' in white (default) color. 
require('my-module')('red');   //should print 'Hello World' in red color. 

文件内容(my-module.js):

// First Call
displayMessage('');

module.exports = function(color){
  // Second Call
  displayMessage(color);
}

// Main function
function displayMessage(clr){
  ... console in provided clr 
}
  1. [require('my-module')仅使用默认颜色进行首次调用。

  2. 这两个调用均发生在[[require('my-module')('red')] >>中,一次不使用/默认值,接下来一次使用红色参数。

  3. 如果我将第一个函数调用移到单独的module.exports中:

module.exports = function(){ // First Call displayMessage(''); }

require('my-module')

上根本没有调用。
如果我可以得到一个区分两个调用的指标,则可能可以相应地添加条件。

我的查询:如何区分所需的模块中是否包含参数?详细信息:我编写了一个模块,该模块将以彩色(作为参数传递)来管理消息。如果...

javascript node.js require
2个回答
0
投票
require('my-module')('red'); ,将使用'red'参数调用函数一次;

0
投票
[无论何时需要模块,都将加载并调用它。如果要使用具有默认值的默认方法,则可以有条件地使其不包含arg,或者仅导出方法本身。

module.exports = function() { // First Call displayMessage(''); } module.exports = function(color){ // Second Call displayMessage(color); } // Main function function displayMessage(clr){ ... console in provided clr }

编辑:

根据注释,不可能从各处调用无参数构造函数。因此,您需要确定带有一个标志。

   var argCall = false;
   module.exports = function(color) {
         // Second Call
        argCall = true;
        displayMessage(color);
    }

    if (!argCall) {
          // First Call
          displayMessage('');
    }

    // Main function
   function displayMessage(clr){
         ... console in provided clr 
   }

现在它无需呼叫就可以使用,

require('my-module') // will go through FIRST CALL require('my-module')('red') // will go with SECOND CALL only

© www.soinside.com 2019 - 2024. All rights reserved.