How can NodeJS local modules be obtained?

  node.js, question

The company recently split up at the front and back ends. I don’t know much about NodeJS. I am at the back end.

When sorting out the front-end application framework (based on Express), I encountered a very simple problem. The specific problems are as follows:

I have created a new lib folder under the root directory of the project. This folder has many modules of my own. The problem has arisen. How can we inside these other modules of our own?

Is there a convenient method of introduction? For example:

jsvar config = require('lib/config');
 var util = require('lib/util');

LikerequireNode_modules as convenient as modules.

jsvar fs = require('fs');

Is there a flexible solution that can be easily introduced, because business modularity is considered later, and many modules may have a deeper hierarchy. In this case, relative path dependence should not be appropriate?

Some points:

  1. Require is used by default__dirnameAs the starting path. SeeAlgorithm Interpretation of module
  2. Fs is adopted by default.process.cwd()As the starting path. SeeDocuments for fs

If LZ asks how to locate the root directory of the project and has a common reference method, there are two common methods.

one

app.js

var _rootDir = __dirname;
 Object.defineProperty(global, "ROOT_DIR", {
 get: function(){
 return _rootDir;
 bracket
 });

module.js

var path = require("path") ;
 var ADDR_PREFIX = path.join(global.ROOT_DIR , "to/your/path") ;

2

module.js

var path = require("path") ;
 var ADDR_PREFIX = path.join(process.cwd() , "to/your/path") ;

The first is more robust. Where app.js is located__dirnameIs an absolute path address, andprocess.cwd()(or in the path stringFull stopSuggested paths) may change.