├── .npmrc ├── .gitattributes ├── .gitignore ├── fixtures ├── filepath │ ├── 1.js │ ├── 2.js │ └── 3.js ├── main │ ├── 1.js │ └── 2.js ├── esm-top-level │ └── test.js └── no-match │ └── test.js ├── .github ├── funding.yml ├── security.md └── workflows │ └── main.yml ├── index.test-d.ts ├── .editorconfig ├── test.js ├── index.d.ts ├── index.js ├── package.json ├── license └── readme.md /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | yarn.lock 3 | -------------------------------------------------------------------------------- /fixtures/filepath/1.js: -------------------------------------------------------------------------------- 1 | import x from './2.js'; 2 | 3 | x(); 4 | -------------------------------------------------------------------------------- /fixtures/main/1.js: -------------------------------------------------------------------------------- 1 | import two from './2.js'; 2 | 3 | two(); 4 | -------------------------------------------------------------------------------- /fixtures/esm-top-level/test.js: -------------------------------------------------------------------------------- 1 | import parentModule from '../../index.js'; 2 | 3 | console.log(parentModule() ?? 'undefined'); 4 | -------------------------------------------------------------------------------- /fixtures/filepath/2.js: -------------------------------------------------------------------------------- 1 | import three from './3.js'; 2 | 3 | export default function two() { 4 | three(import.meta.url); 5 | } 6 | -------------------------------------------------------------------------------- /fixtures/main/2.js: -------------------------------------------------------------------------------- 1 | import parentModule from '../../index.js'; 2 | 3 | export default function two() { 4 | console.log(parentModule()); 5 | } 6 | -------------------------------------------------------------------------------- /.github/funding.yml: -------------------------------------------------------------------------------- 1 | github: sindresorhus 2 | open_collective: sindresorhus 3 | custom: https://sindresorhus.com/donate 4 | tidelift: npm/parent-module 5 | -------------------------------------------------------------------------------- /fixtures/filepath/3.js: -------------------------------------------------------------------------------- 1 | import parentModule from '../../index.js'; 2 | 3 | export default function three(filepath) { 4 | console.log(parentModule(filepath)); 5 | } 6 | -------------------------------------------------------------------------------- /index.test-d.ts: -------------------------------------------------------------------------------- 1 | import {expectType} from 'tsd'; 2 | import parentModule from './index.js'; 3 | 4 | expectType(parentModule()); 5 | expectType(parentModule('foo')); 6 | -------------------------------------------------------------------------------- /.github/security.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. 4 | -------------------------------------------------------------------------------- /fixtures/no-match/test.js: -------------------------------------------------------------------------------- 1 | import parentModule from '../../index.js'; 2 | 3 | // Test filePath that doesn't exist in the call stack 4 | const result = parentModule('/nonexistent/path.js'); 5 | console.log(result ?? 'undefined'); 6 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = tab 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | 10 | [*.yml] 11 | indent_style = space 12 | indent_size = 2 13 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | - push 4 | - pull_request 5 | jobs: 6 | test: 7 | name: Node.js ${{ matrix.node-version }} 8 | runs-on: ubuntu-latest 9 | strategy: 10 | fail-fast: false 11 | matrix: 12 | node-version: 13 | - 16 14 | steps: 15 | - uses: actions/checkout@v2 16 | - uses: actions/setup-node@v2 17 | with: 18 | node-version: ${{ matrix.node-version }} 19 | - run: npm install 20 | - run: npm test 21 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | import path from 'node:path'; 2 | import test from 'ava'; 3 | import execa from 'execa'; 4 | 5 | test('main', async t => { 6 | const {stdout} = await execa('node', ['./fixtures/main/1.js']); 7 | t.is(path.basename(stdout), '1.js'); 8 | }); 9 | 10 | test('filePath option', async t => { 11 | const {stdout} = await execa('node', ['./fixtures/filepath/1.js']); 12 | t.is(path.basename(stdout), '1.js'); 13 | }); 14 | 15 | test('ESM top-level returns undefined', async t => { 16 | const {stdout} = await execa('node', ['./fixtures/esm-top-level/test.js']); 17 | t.is(stdout.trim(), 'undefined'); 18 | }); 19 | 20 | test('filePath not in stack returns undefined', async t => { 21 | const {stdout} = await execa('node', ['./fixtures/no-match/test.js']); 22 | t.is(stdout.trim(), 'undefined'); 23 | }); 24 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | Get the path of the parent module. 3 | 4 | @param filePath - The file path of the module for which to get the parent path. Default: `import.meta.filename` 5 | 6 | Useful for getting the parent of a specific module when the call traverses [multiple module levels](https://github.com/sindresorhus/parent-module/tree/main/fixtures/filepath). 7 | 8 | @returns The file path of the parent module, or `undefined` if there is no parent module (for example, when called from the top-level of an entry module). 9 | 10 | @example 11 | ``` 12 | // bar.js 13 | import parentModule from 'parent-module'; 14 | 15 | export default function bar() { 16 | console.log(parentModule()); 17 | //=> '/Users/sindresorhus/dev/unicorn/foo.js' 18 | } 19 | 20 | // foo.js 21 | import bar from './bar.js'; 22 | 23 | bar(); 24 | ``` 25 | */ 26 | export default function parentModule(filePath?: string): string | undefined; 27 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | import callsites from 'callsites'; 2 | 3 | function isValidFileName(fileName) { 4 | return typeof fileName === 'string' 5 | && !fileName.startsWith('node:') 6 | && fileName !== 'module.js'; 7 | } 8 | 9 | export default function parentModule(filePath) { 10 | const stacks = callsites(); 11 | 12 | if (!filePath) { 13 | // Find the first non-internal parent module 14 | for (const stack of stacks.slice(2)) { 15 | const fileName = stack?.getFileName(); 16 | 17 | if (isValidFileName(fileName)) { 18 | return fileName; 19 | } 20 | } 21 | 22 | return; 23 | } 24 | 25 | let hasSeenValue = false; 26 | 27 | // Start from index 1 to skip this function 28 | for (const stack of stacks.slice(1)) { 29 | const parentFilePath = stack?.getFileName(); 30 | 31 | if (!isValidFileName(parentFilePath)) { 32 | continue; 33 | } 34 | 35 | if (parentFilePath === filePath) { 36 | hasSeenValue = true; 37 | continue; 38 | } 39 | 40 | if (hasSeenValue) { 41 | return parentFilePath; 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "parent-module", 3 | "version": "3.2.0", 4 | "description": "Get the path of the parent module", 5 | "license": "MIT", 6 | "repository": "sindresorhus/parent-module", 7 | "funding": "https://github.com/sponsors/sindresorhus", 8 | "author": { 9 | "name": "Sindre Sorhus", 10 | "email": "sindresorhus@gmail.com", 11 | "url": "https://sindresorhus.com" 12 | }, 13 | "type": "module", 14 | "exports": "./index.js", 15 | "engines": { 16 | "node": "^12.20.0 || ^14.13.1 || >=16.0.0" 17 | }, 18 | "scripts": { 19 | "test": "xo && ava && tsd" 20 | }, 21 | "files": [ 22 | "index.js", 23 | "index.d.ts" 24 | ], 25 | "keywords": [ 26 | "parent", 27 | "module", 28 | "package", 29 | "caller", 30 | "calling", 31 | "module", 32 | "path", 33 | "callsites", 34 | "callsite", 35 | "stacktrace", 36 | "stack", 37 | "trace", 38 | "function", 39 | "file" 40 | ], 41 | "dependencies": { 42 | "callsites": "^4.1.0" 43 | }, 44 | "devDependencies": { 45 | "ava": "^3.15.0", 46 | "execa": "^5.1.1", 47 | "tsd": "^0.17.0", 48 | "xo": "^0.45.0" 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Sindre Sorhus (https://sindresorhus.com) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # parent-module 2 | 3 | > Get the path of the parent module 4 | 5 | This module provides a reliable way to get the file path of the module that called your code, working correctly with both CommonJS and ESM modules. 6 | 7 | ## Install 8 | 9 | ```sh 10 | npm install parent-module 11 | ``` 12 | 13 | ## Usage 14 | 15 | ```js 16 | // bar.js 17 | import parentModule from 'parent-module'; 18 | 19 | export default function bar() { 20 | console.log(parentModule()); 21 | //=> '/Users/sindresorhus/dev/unicorn/foo.js' 22 | } 23 | ``` 24 | 25 | ```js 26 | // foo.js 27 | import bar from './bar.js'; 28 | 29 | bar(); 30 | ``` 31 | 32 | ## API 33 | 34 | ### parentModule(filePath?) 35 | 36 | Returns: `string | undefined` 37 | 38 | Returns the file path of the immediate parent module, or `undefined` if there is no parent module (for example, when called from the top-level of an entry module). 39 | 40 | #### filePath 41 | 42 | Type: `string`\ 43 | Default: `import.meta.filename` 44 | 45 | The file path of the module for which to get the parent path. 46 | 47 | Useful for getting the parent of a specific module when the call traverses [multiple module levels](fixtures/filepath). 48 | 49 | ## Tip 50 | 51 | Combine it with [`read-package-up`](https://github.com/sindresorhus/read-package-up) to read the package.json of the parent module. 52 | 53 | ```js 54 | import path from 'node:path'; 55 | import {readPackageUpSync} from 'read-package-up'; 56 | import parentModule from 'parent-module'; 57 | 58 | const parent = parentModule(); 59 | if (parent) { 60 | console.log(readPackageUpSync({cwd: path.dirname(parent)}).pkg); 61 | //=> {name: 'chalk', version: '1.0.0', …} 62 | } 63 | ``` 64 | --------------------------------------------------------------------------------