Node: Transition from __dirname to import.meta.url could be better documented

Created on 7 Jun 2019  路  2Comments  路  Source: nodejs/node

Relevant doc:
https://nodejs.org/dist/latest/docs/api/esm.html#esm_no_code_require_code_code_exports_code_code_module_exports_code_code_filename_code_code_dirname_code

using --experimental-modules

We could improve the documentation:
import.meta.url is not an _equivalent_ of __dirname several lines of code are required to make it work.

Here's my current workaround, if you have a better way of doing please share:

import path from "path";
// same as previous __dirname, substring(8) removes the file:/// that is at the beginning
const dirname__ = path.dirname(import.meta.url.substring(8));

const x = readFileSync(`${dirname__}/x.html`, `utf8`);

Describe the solution you'd like
Add a few lines in the doc on how to transition from __dirname to import.meta.url

Describe alternatives you've considered
Otherwise provide import.meta.__dirname for even easier transition

Most helpful comment

@GrosSacASac You are exactly right this is an important transition to document, so thank you for bringing this up. Note that your example is not correct - you should use the following pattern rather in Node.js:

import { fileURLToPath } from 'url';
const __dirname = fileURLToPath(import.meta.url);

See https://nodejs.org/dist/latest-v12.x/docs/api/url.html#url_url_fileurltopath_url for more info on this method.

If you'd be interested in submitting a docs PR to clarify the section you linked, please do, that would definitely be useful.

All 2 comments

@GrosSacASac You are exactly right this is an important transition to document, so thank you for bringing this up. Note that your example is not correct - you should use the following pattern rather in Node.js:

import { fileURLToPath } from 'url';
const __dirname = fileURLToPath(import.meta.url);

See https://nodejs.org/dist/latest-v12.x/docs/api/url.html#url_url_fileurltopath_url for more info on this method.

If you'd be interested in submitting a docs PR to clarify the section you linked, please do, that would definitely be useful.

Thanks I'll do some something

Was this page helpful?
0 / 5 - 0 ratings