Back to blog

Node.js: How to Create Your First Server

Hello HaWkers! In today's article, we will learn how to create our first server with Node.js.

Advertisement

What is Node.js?

Node.js is an open source platform that allows developers to run JavaScript on the server side. Previously, JavaScript was a client-side-only language used primarily to manipulate page elements and make dynamic interactions.

Installation

To install Node.js, visit the official website and download the latest version compatible with your operating system.

Creating the server

Let's start by creating a new file called server.js. In this file, we will include the Node.js HTTP module, which allows us to transfer data over the Internet.

const http = require('http');

Then we create the server:

const server = http.createServer((req, res) => {  res.statusCode = 200;  res.setHeader('Content-Type', 'text/html');  res.end('<h1>Hello, World!</h1>');});

Here, the createServer function is being used to create a server object. The function passed as an argument will be executed each time an HTTP request is received.

Finally, we need to set the server to listen on a specific port:

const port = 3000;server.listen(port, () => {  console.log(`Server running at http://localhost:${port}/`);});

Now, if you run node server.js in the terminal, you will see the message "Server running at http://localhost:3000/ " and if you open this URL in the browser , you will see the message "Hello, World!".

Conclusion

Congratulations! You've created your first server with Node.js. With this foundation, you can begin to further explore what's possible with Node.js and back-end development. And remember: practice makes perfect!

If you want to learn more about JavaScript and its tools, take a look at the article about Webpack: Mastering the Module Packer.

Advertisement

Until next time, HaWkers!

Let's go up! 🦅

Previous post Next post

Comments (0)

This article has no comments yet 😢. Be the first! 🚀🦅

Add comments