You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.4 KiB

3 years ago
  1. # parent-module [![Build Status](https://travis-ci.org/sindresorhus/parent-module.svg?branch=master)](https://travis-ci.org/sindresorhus/parent-module)
  2. > Get the path of the parent module
  3. Node.js exposes `module.parent`, but it only gives you the first cached parent, which is not necessarily the actual parent.
  4. ## Install
  5. ```
  6. $ npm install parent-module
  7. ```
  8. ## Usage
  9. ```js
  10. // bar.js
  11. const parentModule = require('parent-module');
  12. module.exports = () => {
  13. console.log(parentModule());
  14. //=> '/Users/sindresorhus/dev/unicorn/foo.js'
  15. };
  16. ```
  17. ```js
  18. // foo.js
  19. const bar = require('./bar');
  20. bar();
  21. ```
  22. ## API
  23. ### parentModule([filepath])
  24. By default, it will return the path of the immediate parent.
  25. #### filepath
  26. Type: `string`<br>
  27. Default: [`__filename`](https://nodejs.org/api/globals.html#globals_filename)
  28. Filepath of the module of which to get the parent path.
  29. Useful if you want it to work [multiple module levels down](https://github.com/sindresorhus/parent-module/tree/master/fixtures/filepath).
  30. ## Tip
  31. Combine it with [`read-pkg-up`](https://github.com/sindresorhus/read-pkg-up) to read the package.json of the parent module.
  32. ```js
  33. const path = require('path');
  34. const readPkgUp = require('read-pkg-up');
  35. const parentModule = require('parent-module');
  36. console.log(readPkgUp.sync({cwd: path.dirname(parentModule())}).pkg);
  37. //=> {name: 'chalk', version: '1.0.0', …}
  38. ```
  39. ## License
  40. MIT © [Sindre Sorhus](https://sindresorhus.com)