在node.js中为require设置路径

时间:2015-11-15 16:55:21

标签: javascript node.js

我有这样的文件夹结构。

  • 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中搜索其模块。

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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 :(得分:0)

如果您想添加 /foo/bar 到要求:

  • 通过编辑 process.env.NODE_PATH

那么你的 js 文件应该位于 /foo/bar/node_modules/

process.env.NODE_PATH = '/foo/bar' + ':' + process.env.NODE_PATH;
  • 通过编辑 process.mainModule.paths

那么你的 js 文件应该位于 /foo/bar/

process.mainModule.paths[process.mainModule.paths.length] = '/foo/bar';