Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Node Require and Import

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading