• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# read-package-tree
2
3[![Build Status](https://travis-ci.org/npm/read-package-tree.svg?branch=master)](https://travis-ci.org/npm/read-package-tree)
4
5Read the contents of node_modules.
6
7## USAGE
8
9```javascript
10var rpt = require ('read-package-tree')
11rpt('/path/to/pkg/root', function (node, kidName) {
12  // optional filter function– if included, each package folder found is passed to
13  // it to see if it should be included in the final tree
14  // node is what we're adding children to
15  // kidName is the directory name of the module we're considering adding
16  // return true -> include, false -> skip
17}, function (er, data) {
18  // er means that something didn't work.
19  // data is a structure like:
20  // {
21  //   package: <package.json data, or an empty object>
22  //   package.name: defaults to `basename(path)`
23  //   children: [ <more things like this> ]
24  //   parent: <thing that has this in its children property, or null>
25  //   path: <path loaded>
26  //   realpath: <the real path on disk>
27  //   isLink: <set if this is a Link>
28  //   target: <if a Link, then this is the actual Node>
29  //   error: <if set, the error we got loading/parsing the package.json>
30  // }
31})
32
33// or promise-style
34rpt('/path/to/pkg/root').then(data => { ... })
35```
36
37That's it.  It doesn't figure out if dependencies are met, it doesn't
38mutate package.json data objects (beyond what
39[read-package-json](http://npm.im/read-package-json) already does), it
40doesn't limit its search to include/exclude `devDependencies`, or
41anything else.
42
43Just follows the links in the `node_modules` hierarchy and reads the
44package.json files it finds therein.
45
46## Symbolic Links
47
48When there are symlinks to packages in the `node_modules` hierarchy, a
49`Link` object will be created, with a `target` that is a `Node`
50object.
51
52For the most part, you can treat `Link` objects just the same as
53`Node` objects.  But if your tree-walking program needs to treat
54symlinks differently from normal folders, then make sure to check the
55object.
56
57In a given `read-package-tree` run, a specific `path` will always
58correspond to a single object, and a specific `realpath` will always
59correspond to a single `Node` object.  This means that you may not be
60able to pass the resulting data object to `JSON.stringify`, because it
61may contain cycles.
62
63## Errors
64
65Errors parsing or finding a package.json in node_modules will result in a
66node with the error property set.  We will still find deeper node_modules
67if any exist. *Prior to `5.0.0` these aborted tree reading with an error
68callback.*
69
70Only a few classes of errors are fatal (result in an error callback):
71
72* If the top level location is entirely missing, that will error.
73* if `fs.realpath` returns an error for any path its trying to resolve.
74