0

I'm trying to use an email template while sending emails. here's my project structure.

project-name
  client
  server
    email-templates
      confirm-email.html
    controllers
      accounts.js (currently here)

I am reading the template file like so.

fs.readFile('../email-templates/confirm-email.html', async (error, html) => {
  // do some stuff
})

I think have entered a correct path. but still I get an error.

Error: ENOENT: no such file or directory

I have checked other questions on SO. but they are using the variable __dirname because I am using ES6 modules I don't have access to that variable.

// package.json
"type": "module",

any suggestions ?

Xaarth
  • 1,021
  • 3
  • 12
  • 34

2 Answers2

2

Try to use path module to resolve the absolute path the file when you are trying to access the file.

fs.readFile(path.resolve(__dirname, '../email-templates/confirm-email.html'), function(err, html) {// do some stuff})
Ayzrian
  • 2,279
  • 1
  • 7
  • 14
  • I'm using es6 modules. I don't have access to `__dirname` variable. – Xaarth May 26 '21 at 08:49
  • It is strange, every Node.js module should have `__dirname` variable. You need fix that. – Ayzrian May 26 '21 at 08:51
  • I have `"type": "module",` in my `package.json` that's why – Xaarth May 26 '21 at 08:51
  • @vajad57 you can have a look here https://stackoverflow.com/questions/46745014/alternative-for-dirname-in-node-when-using-the-experimental-modules-flag Try using the URL file access notation to build the correct `__dirname` for your case – Freeman Lambda May 26 '21 at 09:01
1

I don't have access to __dirname because I'm using ES6 modules. I've used path.resolve() instead which fixed the error.

fs.readFile(
  path.join(path.resolve(), 'email-templates', 'confirm-email.html'),
  'utf8',
  (error, html) => {
    // do some stuff
  }
);

to get access of the __dirname variable when can do:

const __dirname = path.resolve();
Xaarth
  • 1,021
  • 3
  • 12
  • 34