Xaarth
Xaarth

Reputation: 1151

Node JS - no such file or directory filesystem module

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 ?

Upvotes: 0

Views: 1148

Answers (2)

Xaarth
Xaarth

Reputation: 1151

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();

Upvotes: 1

Ayzrian
Ayzrian

Reputation: 2465

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})

Upvotes: 3

Related Questions