← Back
__dirname es6 modules nodejs

Use ES6 modules with node

You can use ES6 modules starting from Node 16 by adding this to package.json:

{
"type": "module",
...
}

But, if you're creating scripts, remember __dirname is not defined.

Here's a way to define for us:

import { join, dirname } from "path";
import { fileURLToPath } from "url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

Resources: