Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the module path in Node.js

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what is the module path in Node.js". In daily operation, I believe many people have doubts about how the module path in Node.js is. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how the module path in Node.js is". Next, please follow the editor to study!

Require case

There is currently a project

Current project path / Users/rainbow/Documents/ front end / scaffolding development / rainbow-test

There is a pile of files in the bin directory of the project

/ bin/index.js

Console.log (require.resolve (".")); / / Users/rainbow/Documents/ front end / scaffolding development / rainbow-test/bin/index.js output bin/index.js absolute path console.log (require.resolve.paths (".")); / / ['/ Users/rainbow/Documents/ front end / scaffolding development / rainbow-test/bin'] an array of console.log (require.resolve ("scaffolding")) where the output files may be located / / Users/rainbow/Documents/ front end / scaffolding development / rainbow-test/node_modules/yargs/index.cjsconsole.log (require.resolve.paths ("yargs")) / * ['/ Users/rainbow/Documents/ front end / scaffolding development / rainbow-test/bin/node_modules','/ Users/rainbow/Documents/ front end / scaffolding development / rainbow-test/node_modules','/ Users/rainbow/Documents/ front end / scaffolding development / node_modules','/ Users/rainbow/Documents/ front end / node_modules','/ Users/rainbow/Documents/node_modules','/ Users/rainbow/node_modules' '/ Users/node_modules',' / node_modules','/ Users/rainbow/.node_modules','/ Users/rainbow/.node_libraries','/ usr/local/Cellar/node/14.3.0_1/lib/node'] * / require parses and finds the process of the module execution file

1. The path resolution of Nodejs project module is realized by require.resolve.

Require.resolve is realized through the Module._resolveFileName method.

The core process of Module._resolveFileName is:

Determine whether the path is a built-in module

No, then use the Module._resolveLookupPahts method to generate the possible paths of node_modules. If the passed path is'/ test/lerna/cli.js', add the path array of node_moduels under each level path.

Query the real path of the module through Module._findPath

2. The core process of Module._findPath is:

Query cache (merge request and paths to generate cacheKey via\ X00)

Traverses the paths array generated by the Module._resolveLookupPahts method, and forms the file path basePath between path and request

If basePath exists, call fs.realPahtSync to get the real path of the file.

Cache the real path of the file to Module._pathCache (key is cacheKey) (Module._pathCache is a map)

3. Fs.realPahtSync core process:

Query cache (the cached key is p. That is, the path generated in Module._findPath)

Traverse the path string from left to right, and when querying /, split the path to determine whether the path is a soft link. If it is a soft link, query the real link and generate a new path p, and then continue traversing. Here is a detail:

The subpath base generated during traversal is cached in knownHard and cache to avoid repeated queries.

After traversing, the real path corresponding to the module is obtained. In this case, the original path original is saved in the cache as key, and the real path is saved as value.

4. Require.resolve.paths is equivalent to Module._resolveLookupPaths. This method gets all the possible paths of node_modules to form an array.

5. The implementation principle of require.resolve.paths is as follows:

If it is / (root path), return ['/ node_modules'] directly

Otherwise, traverse the path string from back to front, when the query reaches /, split the path, add node_modules at the end, and pass in a paths array until the paths array is returned after the query does not reach /

Require uses the method of the built-in module

When we use require ('yargs')

Require method

The Module._load method is actually used.

Module.prototype.require = function (id) {/ / id = 'yargs' validateString (id,' id'); if (id =') {throw new ERR_INVALID_ARG_VALUE ('id', id,' must be a non-empty string');} requireDepth++; try {return Module._load (id, this, / * isMain * / false);} finally {requireDepth--;}} / / Parameter id = 'yargs'this= {paths: Module._nodeModulePaths (process.cwd ())}

Module._nodeModulePaths method

/ / enter the logic where the mac computer is located: / / from = > / Users/rainbow/Documents/ front end / scaffolding development / lerna source code / lernas / / 'from' is the _ _ dirname of the module. Module._nodeModulePaths = function (from) {from = path.resolve (from); / / Return early not only to avoid unnecessary work, but to * avoid* returning / / an array of two items for a root: ['/ / node_modules','/ node_modules'] if (from = ='/') return ['/ node_modules']; const paths = [] / / key algorithm code for (let I = from.length-1, p = 0, last = from.length; I > = 0;-- I) {const code = from.charCodeAt (I); if (code = CHAR_FORWARD_SLASH) {if (p! = = nmLen) paths.push (from.slice (0, last) +'/ node_modules'); last = I; p = 0 } else if (p! =-1) {if (nmChars [p] = code) {+ + p;} else {p =-1;}} / / Append / node_modules to handle root paths. Paths.push ('/ node_modules'); return paths;}

Analysis of the core algorithm of for loop:

Module._load method

Module._load (id, this, / * isMain * / false)

The core implementation code is: const filename = Module._resolveFilename (request, parent, isMain)

Require.resolve

The path resolution of Node.js project module is realized by require.resolve.

Require.resolve is realized through the Module._resolveFileName method.

/ / node.js built-in module require source code function resolve (request, options) {validateString (request, 'request'); return Module._resolveFilename (request, mod, false, options); / / Core implementation} require.resolve = resolve;function paths (request) {validateString (request,' request'); return Module._resolveLookupPaths (request, mod); / / Core Code} resolve.paths = paths

Module._resolveFileName core process

Determine whether the path is a built-in module

No, use the Module._resolveLookupPahts method to combine the paths with the path in the environment

Query the real path of the module through Module._findPath

Return Module._resolveFilename (request, parent, isMain)

Module._resolveFilename = function (request, parent, isMain, options) {if (NativeModule.canBeRequiredByUsers (request)) {/ / whether it is a built-in module return request;} let paths; / / combine paths with paths in environment variables paths = Module._resolveLookupPaths (request, parent) / / the core code if (parent & & parent.filename) {/ / reads the package.json file corresponding to filename to see if there is an exports field, current filename = false const filename = trySelf (parent.filename, request); if (filename) {/ / false const cacheKey = request +'\ x00' + (paths.length = 1? Paths [0]: paths.join ('\ x00'); Module._ pathCache [cacheKey] = filename; return filename;}} / / key code, find the local execution file / / Look up the filename first, since that's the cache key. Const filename = Module._findPath (request, paths, isMain, false); if (filename) return filename; / /...}

Module._resolveLookupPahts method

Generate an array of paths where node_modules may exist on all paths of the module to be found

Core implementation method of require.resolve.paths ("yargs")

Generate

['/ Users/rainbow/Documents/ front end / scaffolding development / rainbow-test/bin/node_modules','/ Users/rainbow/Documents/ front end / scaffolding development / rainbow-test/node_modules','/ Users/rainbow/Documents/ front end / scaffolding development / node_modules','/ Users/rainbow/Documents/ front end / node_modules','/ Users/rainbow/Documents/node_modules','/ Users/rainbow/node_modules' '/ Users/node_modules',' / node_modules','/ Users/rainbow/.node_modules','/ Users/rainbow/.node_libraries','/ usr/local/Cellar/node/14.3.0_1/lib/node']

Module._resolveLookupPaths = function (request, parent) {if (NativeModule.canBeRequiredByUsers (request)) {debug ('looking for% j in []', request); return null;} / / Check for node modules paths. If (request.charAt (0)! = ='.'| (request.length > 1 & & request.charAt (1)! = ='.'& & request.charAt (1)! ='/'& & (! isWindows | | request.charAt (1)! = ='\')) {let paths = modulePaths; if (parent! = null & parent.paths & parent.paths.length) {paths = parent.paths.concat (paths) } debug ('looking for j in% jacks, request, paths); return paths.length > 0? Paths: null;} / / In REPL, parent.filename is null. If (! parent | |! parent.id | |! parent.filename) {/ / Make require ('. / path/to/foo') work-normally the path is taken / / from realpath (_ _ filename) but in REPL there is no filename const mainPaths = ['.]; debug ('looking for% j in% jacks, request, mainPaths); return mainPaths;} debug (' RELATIVE: requested:% s from parent.id% slots, request, parent.id) Const parentDir = [path.dirname (parent.filename)]; debug ('looking for% jacks, parentDir); return parentDir;}

Module._findPath core process

Query cache (merge request and paths into cacheKey via\ x00) (\ x00 is the hexadecimal of spaces)

Traverses the paths array generated by the Module._resolveLookupPahts method, and forms the file path basePath between path and request

If basePath exists, call fs.realPahtSync to get the real path of the file.

Fs.realPahtSync

At this point, the study of "what is the module path in Node.js" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report