2015-11-15 91 views
0

我有這樣的文件夾結構。在node.js中設置require的路徑

  • include/

    • index.js
    • plugin/

      • plugin.js
      • helper.js

其中: -

包括/ index.js

//Function for mapping the path of "require" statement in the plugin.js file. 

var mapRequirePath = function(){ 

    var plugins = require('./plugin/plugin'); 
    return plugins; 
} 

//Now call the plugins.. 
var plugin = mapRequirePath(); 

包括/插件/ plugin.js

/* 
     I want all four require statements to point to the same file location '/include/plugin/helper.js' 

     i.e search in the same folder location for module irrespective of the '../' or '../../' present in the require statement 
    */ 

    var helper1 = require('./helper'); 
    var helper2 = require('helper'); 
    var helper3 = require('../../helper'); 
    var helper4 = require('../helper'); 

我想將require的路徑映射到plugin.js文件中,以便所有需要調用的應在same directory only中搜索其模塊。

回答

2

您可能能夠動態改變NODE_PATH環境變量:

// First take a backup: 
var _NODE_PATH = process.env.NODE_PATH; 
// Add /includes/plugin to the path, also note that we need to support 
// `require('../hello.js')`. We can do that by adding /includes/plugin/a, 
// /includes/plugin/a/b, etc.. to the list 
process.env.NODE_PATH+=':/includes/plugin:/includes/plugin/a'; 
// Do your think... 
require('./plugins/plugin'); 
// Restore NODE_PATH 
process.env.NODE_PATH = _NODE_PATH; 
2

嘗試通過命令行來改變NODE_PATH變量:

exports NODE_PATH=directoryYouWant 

如果你不想有改變它爲每一個其他項目,你可以嘗試只在動態你.js文件作修改:

var currentNodePath = process.env.NODE_PATH; 
process.env.NODE_PATH = directoryYouWant; 
//do stuff then change it back 
process.env.NODE_PATH = currentNodePath; 
+0

這將改變所有文件系統的節點路徑。我只是想在'/ include/plugin文件夾內的'require'調用的情況下改變它' –

+0

這可能會奏效,爲好的想法+1。但是你真的測試過它嗎? – andlrc

+0

我看到我們有一個類似的想法:) –