Home > Software engineering >  How to point to Html folder from path module Node Js
How to point to Html folder from path module Node Js

Time:03-23

I want to send html file as response using express so to do that I need to give the position or path of index.html file.

so this is my file structure -

MyWebsite 
     Html
        index.html
     Css
        index.css
     Js
       index.js

if you still not understanding the file structure this the image of file structure :

enter image description here

so in my JavaScript I have written something like this :

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

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

const app = express();

const port = process.env.port || 8080;

app.get('/', (req, res) => {
  const htmlFile = path.join(__dirname, '/index.html');
  res.sendFile(htmlFile)
});

app.listen(port);

giving error -

Error: ENOENT: no such file or directory, stat 'F:\Websites\MyWebsite\js\index.html'

It is not working!. I am unable to give the path or folder name! how can I get the index.html folder's path

any help will be appreciated!

CodePudding user response:

its simple you have set back-word so server can find you index.html change your code to

app.get('/', (req, res) => {
   const htmlFile = path.join(__dirname, '/index.html');
   res.sendFile(htmlFile)
});

new Code Will Be

app.get('/', (req, res) => {
  const htmlFile = path.join(__dirname, '../html/index.html');
  res.sendFile(htmlFile)
});

i hope its work for you ita work for me

CodePudding user response:

you can use 'path' module to move one directory back.

path.join(__filename, '..', 'html', 'index.html')

this way you will avoid slashes and eliminate problems while running your app in different operating systems.

  • Related