How to run an HTML file using Node js

0 votes
Can you tell me How to run an HTML file using Node.js?
Feb 12 in Node-js by Nidhi
• 11,580 points
57 views

1 answer to this question.

0 votes

1.Install Node.js

2.Create a Project Folder

mkdir html-node-app

cd html-node-app

3.Initialize Node.js

npm init -y

4.Create an HTML File

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8" />

  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

  <title>HTML Code</title>

</head>

<body>

  <h1>Hello, Edureka!</h1>

</body>

</html>

5.Create a Server Using Node.js

const http = require('http');

const fs = require('fs');

const path = require('path');

const server = http.createServer((req, res) => {

  if (req.url === '/') {

    const filePath = path.join(__dirname, 'index.html');

    fs.readFile(filePath, (err, data) => {

      if (err) {

        res.writeHead(500, { 'Content-Type': 'text/plain' });

        res.end('500 - Internal Server Error');

      } else {

        res.writeHead(200, { 'Content-Type': 'text/html' });

        res.end(data);

      }

    });

  }

});

const PORT = process.env.PORT || 3000;

server.listen(PORT, () => {

  console.log(`Server running at http://localhost:${PORT}`);

});

6.Start the server:

node server.js

answered Feb 12 by Navya

Related Questions In Node-js

0 votes
1 answer

How to download a file with Node.js without using third-party libraries?

Hii, You can create an HTTP GET request and pipe ...READ MORE

answered Nov 24, 2020 in Node-js by Niroj
• 82,840 points
1,402 views
0 votes
1 answer

How to create a directory if it doesn't exist using Node.js?

Hello @kartik, Try: var fs = require('fs'); var dir = ...READ MORE

answered Jul 9, 2020 in Node-js by Niroj
• 82,840 points
6,401 views
0 votes
1 answer

How to create an HTTPS server in Node.js?

Hello @kartik, The minimal setup for an HTTPS ...READ MORE

answered Jul 13, 2020 in Node-js by Niroj
• 82,840 points
2,020 views
0 votes
1 answer

How to execute an external program from within Node.js?

Hello @kartik, Exec has memory limitation of buffer ...READ MORE

answered Jul 17, 2020 in Node-js by Niroj
• 82,840 points
4,290 views
0 votes
1 answer

How can I dynamically validate Angular forms based on user input?

Dynamic Form Controls with Validation: In scenarios where ...READ MORE

answered Feb 12 in Angular by Navya
67 views
0 votes
1 answer
0 votes
1 answer

React.js or Elm: Which one should I choose?

Choosing between React.js and Elm depends on ...READ MORE

answered Feb 12 in Node-js by Navya
57 views
0 votes
1 answer

What is the process to parse JSON using Node.js?

You can parse JSON data using the ...READ MORE

answered Feb 10 in Node-js by Navya
68 views
0 votes
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP