Node.js v13.2.0 was released with support for ES Modules. The official announcement explains the overview.
In ES Modules environment, global variables such as require, exports, module.exports, __filename,
__dirname are not available. require, exports, module.exports are no longer necessary in favor
of ESM, but we still need __filename and __dirname which can be calculated from import.meta.url.
To make the migration from commonjs to ES Modules smooth, dirname-filename-esm provides functions
to create __dirname and __filename variables easily in an ES Modules environment.
npm install --save dirname-filename-esmUsage is very straightforward.
// In ".mjs" script or a script under "type": "module" package
import { dirname, filename } from 'dirname-filename-esm';
const __dirname = dirname(import.meta);
const __filename = filename(import.meta);
// Use __dirname and __filename like in a commonjs moduleTwo functions are exported.
dirname()takesimport.metaobject and returns__dirnamevalue of the script.filename()takesimport.metaobject and returns__filenamevalue of the script.
These functions return an empty string if import.meta doesn't have url property.
This package has zero dependency.
This package offers TypeScript support. Since this package is for
ES Modules environment, ensure that module option is set to one of the following values in your tsconfig.json.
es2020or laternode16or later