2015-09-27 24 views
0

在我寫的Ruby程序中,我'需要'在'入口點'文件頂部需要的所有文件和模塊。例如:Node.js:如何使模塊可用於多個文件?

#Sets an absolute path for wherever the program is run from 
#this_file = __FILE__ 
#BASEDIR = File.expand_path(File.join(this_file, '..')) 
this_file = __FILE__ 
this_file_folder_nav = File.join(this_file, '..') 
BASEDIR = File.expand_path(this_file_folder_nav) 


#Required Gems 
require 'ap' 
require 'docx' 
require 'sanitize' 
etc 

#Required files 
require_relative "lib/commodity/stories.rb" 
require_relative 'lib/worldgrowth/worldgrowth.rb' 
require_relative "lib/prices/prices.rb" 
require_relative 'lib/prices/prices_module.rb' 
etc 

I can access all the classes defined in the files above. And I can access classes defined in the 'stories.rb' in pirces_module.rb. All the required gems are accessible in all the files 

問:這是一個好的做法嗎?這對我來說似乎很方便,我想在node.js中做同樣的事情。

但是,我發現我不得不在所有將使用該模塊的文件上編寫var module = require('someModule')。如果我有一個node.js應用程序的入口點文件,是否可以做類似於我在Ruby中做的事情?

回答

2

採取假設你想使核心模塊的「http」提供給您的其他文件。在您的入口點文件中,您可以要求('http')並將該對象附加到global對象。此外,您的入口點文件將需要您可能擁有的其他文件。像這樣:現在

var http = require('http') 
global.http = http; 

var other = require('./other') 

,其他文件訪問HTTP模塊,你可以這樣做:

http.createServer(function (req, res) { 
    res.writeHead(200, {'Content-Type': 'text/plain'}); 
    res.end('Hello World\n'); 
}).listen(1337, "127.0.0.1"); 

console.log('Server running at http://127.0.0.1:1337/'); 
+0

您不應該將模塊附加到全局對象。這破壞了測試能力和封裝,因此強烈不合適。 –

+0

@BrandonSmith我明白了......你將如何着手解決在不同文件中提供模塊的問題?我認爲嘗試做他正在嘗試做的事可能是不好的做法。 –

+0

顯而易見的解決方案是處理不便,並在需要的地方添加需求。一個更清潔的替代方案是創建一個公用事業模塊,導出您經常需要的物品。然後,您可以用一個需求來包含您的實用程序。最後,像Electrolyte這樣的依賴注入器使得需要重複相同的模塊少一點痛苦。 –

2

您可以製作一個需要所有其他模塊的模塊,然後在需要的地方需要它。是這樣的:

var Common = { 
    util: require('util'), 
    fs: require('fs'), 
    path: require('path') 
}; 

module.exports = Common; 

// in other modules 
var Common = require('./common.js'); 

這個例子是從this article

+1

除此之外,現在,這意味着你必須是指一切爲'常見。 util.method()'而不僅僅是'util.method()',在我的書中,它向後而不是向前。我只是在每個文件中做一個簡單的'require()'我需要的所有模塊。它使代碼的其餘部分更簡單。 – jfriend00

+0

這並不能解決使用模塊名稱的需要,它解決了在每個文件上需要三個(或更多)模塊的需求。像這樣,你只需要一次 –

+0

我只想在模塊文件的頂部輸入一次,以包含一個像'var util = require('util');'這樣的模塊,而不必每次都進行額外的輸入在你的方案中使用像'Common.util.method()'這樣的模塊。我只是不認爲你所建議的是淨勝。它將一些'require()'語句保存在一個地方,並且每次在整個模塊中使用一個方法時都會輸入更多的信息。這是我的觀點。我知道你正在試圖回答OP的問題,但我不認爲做這件事會更好。 – jfriend00

相關問題