0

I have a command line utility that's installed as a global NPM package (privately, within our org).

I've noticed that file paths aren't actually relative to the installed location, but to the current working directory. In CommonJS I used __dirname but that's not valid with ESM.

So, when a user installs the package globally, and runs it, the following code errors because it's trying to use the current working directory.

fs.readFileSync('./templates/controller.ejs', 'utf8')

It works fine when I run the script from within the npm package folder itself. How I can always be sure it points to its install location?

EDIT: So far, the only way to do this is:

import { fileURLToPath } from 'url';
const dirname = fileURLToPath(new URL('.', import.meta.url));
const file = path.resolve(dirname, 'templates/controller.ejs')
fs.readFileSync(file, 'utf8')

helion3
  • 34,737
  • 15
  • 57
  • 100
  • Does this answer your question? [Alternative for \_\_dirname in Node.js when using ES6 modules](https://stackoverflow.com/questions/46745014/alternative-for-dirname-in-node-js-when-using-es6-modules) – Matt Jun 22 '22 at 02:01
  • Just confirms the `import.meta.url` approach, which I'm surprised has to be the solution. – helion3 Jun 22 '22 at 02:10

0 Answers0