2015-05-12 45 views
1

我正在嘗試構建我的第一個NodeJS模塊。 這是我在做什麼:NodeJS - 導出多個函數

var text = function(){ 
    this.padRight = function(width, string, padding){ 
     return (width <= string.length) ? string : this.padRight(width, string + padding, padding); 
    }; 
    this.cleanText = function(text){ 
     if (typeof text !== 'undefined') { 
      return text.replace(/(\r\n|\n|\r)/gm,""); 
     } 
     return null; 
    }; 
    this.printOut = function(outputObj){ 
     var module = this, 
      output = ""; 

     outputObj.forEach(function(obj){ 
      switch(obj.type){ 
       case "date" : 
        var date = obj.contents; 
        if(typeof date != "undefined") output += date.toString().substring(4, 25) + "\t"; 
        break; 
       case "string": 
        var string = obj.contents; 
        if(typeof string != "undefined"){ 
         string = module.cleanText(string); 
         if(typeof obj.substring != "undefined" && obj.substring != 0) { 
          string = string.substring(0, obj.substring); 
         } 
         if(typeof obj.padRight != "undefined" && obj.padRight != 0) { 
          string = module.padRight(15, string, " "); 
         } 
         output += string + "\t"; 
        } 
        break; 
      } 
     }); 
     console.log(output); 
    }; 
}; 

module.exports.text = text; 

我想有不同類型的幫手,所以我希望能夠調用此模塊是這樣的:

require("helpers");  
helpers.text.printOut(); 

但我得到的錯誤。

如何在同一個模塊中導出不同的功能並分別調用它們?

感謝

回答

1

的問題是text本身就是一種功能,如你想成爲出口的實例text而不是功能在我看來本身即

module.exports.text = new text(); 
1

您的代碼有點令人困惑,因爲你正在定義一個你正在導出的構造函數(正如James所指出的那樣)。這是令人困惑的,因爲在JS中編寫構造函數是一種慣例。

我會建議,雖然不同於詹姆斯的解決方案,即不導出新的文本(),但導出構造函數本身。 在需要此對象的模塊中,將該模塊導入爲var Text = require('./text');並執行新的Text()部件。導出新的Text()的缺點是你有效地創建了一個單例,而這可能或可能不是你的意圖。 請記住,模塊上的require()只能有效地執行一次,而當不同的模塊加載上述模塊時,它們就是相同的對象。