Automatically track a dependency graph of all commonjs modules in an application
npm i module-dep-graph
Let's say we have the following source code:
// A.jsvar B = ;var C = ;moduleexports = 'I am module A!';
// B.jsvar C = ;var D = ;moduleexports = 'I am module B!';
// C.jsmoduleexports = 'I am module C!';
// D.jsmoduleexports = 'I am module D!';
In the very first file that your program executes, you will want to load
Then, at any point in the execution of your program, you can dynamically pull the dependency graph of all commonjs modules:
var A = ;var deps = ;
At this point, calling
console.log(deps.graph) would produce:
'/absolute/path/to/A.js':key: '/absolute/path/to/A.js'deps: ModuleB ModuleCreverse:'/absolute/path/to/B.js':key: '/absolute/path/to/B.js'deps: ModuleC ModuleDreverse: ModuleA'/absolute/path/to/C.js':key: '/absolute/path/to/C.js'deps:reverse: ModuleB ModuleA'/absolute/path/to/D.js':key: '/absolute/path/to/D.js'deps:reverse: ModuleB
Where we see that
deps.graph is a cyclic graph represented as a set of key-value pairs of the
absolute paths to a module's file, and a node on the graph where each node has:
key: the absolute path of the module's source file
deps: an array of references pointing to the nodes in the graph of each module that this node directly depends on.
reverse: an array of references pointing to the nodes in the graph that directly depend on that node.
Because of the
reverse array, this graph represents an undirected graph of module dependencies.
module-dep-graph export provides two helpful methods:
Returns an array of keys (absolute paths) for every module that the provided module key is a
dependency of, both directly and indirectly (through sub-dependencies). This is done by walking
the graph using the node's
deps// [ '/absolute/path/to/A.js', '/absolute/path/to/B.js' ]
Returns an array of keys (absolute paths) for every module that the provided module key depends on,
both directly and indirectly (through sub-dependencies). This is done by walking the graph using
deps// [ '/absolute/path/to/B.js', '/absolute/path/to/C.js', '/absolute/path/to/D.js' ]
How does it work?
This module works by using Node's internal
module module, and wrapping some of it's internal
methods. Namely, the
Module._load method. Check the source of this repo, as well as the source
of module for more insight.