Node.js Example to Create Web Server
It is the basic code example to create node.js server.
// Importing the http module
const http = require('http');
// Creating a server
const server = http.createServer((req, res) => {
// Setting the content type to HTML
res.writeHead(200, {
'Content-Type': 'text/html'
});
// Sending the HTML response
res.end('<h1>Hello GFG</h1>');
});
// Listening on port 3000
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
Output:
Code Explaination:
- We use the
http
module to create an HTTP server. - The server listens on the specified port and hostname.
- When a new request arrives, the callback function handles it by setting the response status, headers, and content.
Node.js Introduction
Node.js is an open-source and cross-platform JavaScript runtime environment. It is a powerful tool suitable for a wide range of projects. Node.js stands out as a game-changer. Imagine using the power of JavaScript not only in your browser but also on the server side.
Table of Content
- What is Node.JS?
- Why Node.JS?
- Basic Concepts of Node.JS
- Node.js Example to Create Web Server
- How Node.JS Works?
- Advantages of Node.JS
- What is Node.JS file?
- Application of Node.JS
- Common Use Cases of Node.JS
- Node.JS Ecosystem
- Learn more about Node.JS
Contact Us