0
import path from 'path';
import fs from 'fs';

fs.mkdirSync(path.join(__dirname, 'folderName'));

I want to create directories in node, when I require the modules (commonjs) everything works but when I change the type in my package.json to module and use imports the folder doesn't get created, what could I be doing wrong?

Limitless Claver
  • 479
  • 5
  • 17
  • 1
    There is no `__dirname` in an ESM module. You will have to manufacture it from `import.meta.url`. You can search and find examples for how to do that. For examples, see [here](https://stackoverflow.com/a/69242626/816620). – jfriend00 Nov 22 '21 at 02:33

2 Answers2

2

There is no __dirname in an ESM module. If it's something you need, you can manufacture it with this:

import path from 'path';
import { fileURLToPath } from 'url';

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

But, many of the functions in the fs module can take import.meta.url more directly. See this other answer for details on that.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

I figured __dirname isn't available on es6 modules so I just replaced that with './'. You could use an npm package for that if you are looking for elegance.

Limitless Claver
  • 479
  • 5
  • 17
  • 2
    `./` will use the current working directory which may or may not be the same as `__dirname`. In a top level module file in your project, it will be the same thing. In an imported module from the `node_modules` directory, the current working directory will have no connection at all to what `__dirname` would have been. – jfriend00 Nov 22 '21 at 02:46