I need to view a dependency tree of some sort, showing the various require()
s starting at a particular file. For example, if I have a server.js
file like so:
// server.js
var myThing = require('./myThing');
and a myThing.js
file like so:
// myThings.js
var mongodb = require('mongodb');
is there a way to see that mongodb
is required by server.js
without manually traversing through myThing.js
?
I'd love to see a tree something like npm list
generates, eg:
alex@alex-pc ~/repos/test $ npm list
[email protected] /home/alex/repos/test
├─┬ [email protected]
│ ├── [email protected]
│ ├─┬ [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├─┬ [email protected]
│ │ │ └── [email protected]
│ │ ├─┬ [email protected]
│ │ │ └── [email protected]
│ │ └── [email protected]
│ ├── [email protected]
In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.
To get the contents of a file as a string, we can use the readFileSync() or readFile() functions from the native filesystem ( fs ) module in Node. js. /* Get all the contents from a file */ const content = readFileSync("myFile. txt");
The __dirname in a node script returns the path of the folder where the current JavaScript file resides. __filename and __dirname are used to get the filename and directory name of the currently executing file. The ./ gives the current working directory. It works similar to process. cwd() method.
createReadStream('your/file'); var outstream = new stream; var rl = readline. createInterface(instream, outstream); rl. on('line', function(line) { // process line here }); rl. on('close', function() { // do something on finish here });
You can see the dependency tree using madge
dependo
It is not sort, but visualize your files
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With