Skip to content

Instantly share code, notes, and snippets.

@BlazeInferno64
Last active May 30, 2023 16:18
Show Gist options
  • Save BlazeInferno64/61594d38dc37c6bd32bfa5416622a99c to your computer and use it in GitHub Desktop.
Save BlazeInferno64/61594d38dc37c6bd32bfa5416622a99c to your computer and use it in GitHub Desktop.
Node js web server to serve html file
const http = require('http'); // importing the http module
const fs = require('fs'); // importing fs module although I'm not using it in this demo , but just for convenience for the next demo where I would be using it
const hostname = '127.0.0.1'; // Plss note that you can use Localhost instead of this address if you can't memorize it
const port = 80; // Any port where you would like your server to listen , but i recommed you in using port 80 as you don't have to type anything after http://localhost/
const server = http.createServer((req, res) => {
res.statusCode = 200; // Status Code
res.setHeader('Content-Type', 'text/plain'); // Header of the web server
res.end('Hello World !! This a simple Node js Web Server '); // Simple demo with hello world but instead of it you can serve your Html file also
});
server.listen(port, hostname, () => {
console.log(`Server is alive at http://${hostname}:${port}/`); // It will print this in your terminal checkout your server in this address
});
@BlazeInferno64
Copy link
Author

Make sure that you have installed Node js before using this code

If you haven't then Click down below on the link to
get to their homepage for installation

https://nodejs.org/en/download

After you have visited it download the version of node js for your OS

Also, if you have any issues regarding this piece of code just post a comment here

I will be happy to assist you

Thanks for reading :)

Have nice day ahead 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment