Creating an HTTP Web Server using Node.js
Hello Everyone 👋
Thanks for stopping by again! Today, we're going to dive into how you can create a basic HTTP Web Server using Node.js.
Node.js is a runtime environment that lets you run JavaScript code outside the browser, and it's amazing for building fast and scalable network applications.
🛠 Step-by-step: Creating the HTTP Server
Let's start by creating a file called server.js
and write our first HTTP server.
1. Importing the http
module
Node.js comes with a built-in module called http
, which we can use to create web servers.
const http = require('http')
2. Creating the server
We use http.createServer()
method which takes a callback function. This callback gets two parameters: req
(the request object) and res
(the response object).
const server = http.createServer((req, res) => {
res.statusCode = 200
res.setHeader('Content-Type', 'text/plain')
res.end('Hello, World! This is my first Node.js server.')
})
3. Defining the port
We’ll specify the port number where our server will listen:
const PORT = 3000
4. Starting the server
Finally, we’ll make the server listen to the specified port and log a message when it starts:
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`)
})
🧪 Final Code
const http = require('http')
const server = http.createServer((req, res) => {
res.statusCode = 200
res.setHeader('Content-Type', 'text/plain')
res.end('Hello, World! This is my first Node.js server.')
})
const PORT = 3000
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`)
})
💻 Run it Yourself!
- Save this code in a file named
server.js
- Open your terminal and run:
node server.js
- Open your browser and go to http://localhost:3000. You should see: Hello, World! This is my first Node.js server.
You can also experiment and try returning HTML, JSON or even build a small API.
Stay tuned for more cool Node.js stuff coming soon ⚡️