简体   繁体   中英

Best way to load modules node.js

My project has got many folders and I often load my own modules in node.js in the following way:

var request = require("request"),
    config  = require("../../../modules/config"),
    urls    = require("../../../modules/urls");

I sometimes move the folders around and the path changes, so I need to adjust the ../ part manually.

I don't want to move my modules into the node_modules folder, but I'd like to load the modules in the following way:

var request = require("request"),
    config  = require("config"),
    urls    = require("urls");

or

var request = require("request"),
    config  = require("modules/config"),
    urls    = require("modules/urls");

What are my options?

New Answer:

Relative paths seem to be the simplest choice after all, it allows you to run your script from any location.

var config = require("../../config");

Old answer:

I found out that, while not ideal, there's also the possibility to use process.cwd() .

var request = require("request"),
    config  = require(process.cwd() + "/modules/config");

or, if the process.cwd() is set to a global variable in the main js file

global.cwd = process.cwd();

then

var request = require("request"),
    config  = require(global.cwd + "/modules/config"),
    urls    = require(global.cwd + "/modules/urls");

You can try to do the following, based on some conditions

  • if the scripts are exclusively written for your application, meaning it won't work with any other application, and the scripts don't have any dependencies place them under modules directory and try to create expose a variable such as global.basepath and using path.join to construct the filepath and require it.You could also inject module variable after you require them at the main script of your app.

main.js

var config = require('modules/config.js')(_,mongoose,app);

modules/config.js

module.exports=function(_,mongoose,app){
 return function(){
  // _,mongoose,app
  this.loadConfigVariable..
 }
}
  • if the scripts are not one-files that have separate tests, require other vendor modules in order to be executed then create individual node modules and publish them to a registry for convenience when installing the main application. Just as express does, there is the main application express and there are modules that express uses such as express-validation which in turn has its own dependencies.

You could add a symlink in node_modules , pointing to wherever your modules are.

For example, add a symlink named "my_modules", referencing '../foo/bar/my_modules'. Then, your requires will look like

var config = require('my_modules/config');
var urls = require('my_modules/urls');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM