Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

node.js - Change node_modules location

Is there a way to change the node_modules folder location?

For example:

- dir1
- dir2
- node_modules

to:

- dir1
- dir2
    - node_modules
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The following is the code which looks int the node_modules folder by default

Module.prototype.load = function(filename) {
  debug('load ' + JSON.stringify(filename) +
        ' for module ' + JSON.stringify(this.id));

  assert(!this.loaded);
  this.filename = filename;
  this.paths = Module._nodeModulePaths(path.dirname(filename));

  var extension = path.extname(filename) || '.js';
  if (!Module._extensions[extension]) extension = '.js';
  Module._extensions[extension](this, filename);
  this.loaded = true;
};

So, following is the exact search pattern:

  1. Node.JS looks to see if the given module is a core module. (e.g. http, fs, etc.) Always takes the precedence in the loading modules.

  2. If the given module is not a core modules(e.g. http, fs, etc.), Node.js will then begin to search for a directory named, node_modules.

    It will start in the current directory (relative to the currently-executing file in Node.JS) and then work its way up the folder hierarchy, checking each level for a node_modules folder. Once Node.JS finds the node_modules folder, it will then attempt to load the given module either as a (.js) JavaScript file or as a named sub-directory; if it finds the named sub-directory, it will then attempt to load the file in various ways. So, for example

  3. If you make a request to load the module, "utils" and its a directory not a .js file then:
    Node.JS will search a hierarchical directory for node_modules and utils in the following ways:

    ./node_modules/utils.js
    ./node_modules/utils/index.js
    ./node_modules/utils/package.json
    
  4. If Node.JS still can't find the file in above steps, Node.js will then start to look into the directory paths from environment variables i.e. NODE_PATH set on your machine(obviously set by Node.JS installer file if you are on windows) Not Found in all the above steps then, prints a stack trace to stder
    E.g.: Error:Cannot find module 'yourfile'
    For more information: link is here even the cyclic require() is explained very well..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...