Skip to content

Instantly share code, notes, and snippets.

@scagood
Created August 28, 2024 21:14
Show Gist options
  • Save scagood/9a0c71c33519ebcd52d820691ae41e32 to your computer and use it in GitHub Desktop.
Save scagood/9a0c71c33519ebcd52d820691ae41e32 to your computer and use it in GitHub Desktop.
Find the file that was executed in a node program
const { normalize, join } = require('node:path');
/**
* @returns {string}
*/
function findExecutingFile() {
// This is covered in the 'package-eval' tests. Jest just does not know that...
/* istanbul ignore next */
return normalize(
// This is present for `type: commonjs` after startup
require.main?.filename ??
// This is for `--require`, `--import`, and `type: module`
process.argv[1] ??
// This is for node in REPL mode
join(process.cwd(), '.eval'),
);
}
module.exports = { findExecutingFile };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment