Creating first Nodejs Server
Welcome to the fascinating realm of Node.js! Within the current dynamic web development environment, Node.js has become an excellent platform for creating server-side applications that are both scalable and effective. Regardless of your level of experience, Node.js provides a strong foundation for realizing your ideas, whether you’re a beginner wanting to explore the world of backend development or an experienced developer seeking to broaden your skill set.
Let’s have a look at how to make your first Node.js server together in this blog post for beginners. We’ll go over the core ideas of Node.js and walk you through the process of configuring a minimal server that can respond to requests for content and handle HTTP requests.
What to expect from this Blog:
In this tutorial, we’ll start from scratch and guide you through the process of setting up your development environment, writing your first Node.js server code, and running your server locally. By the end of this tutorial, you’ll have a solid understanding of how to create a basic server using Node.js and be well-equipped to explore more advanced topics in web development.
So, without further ado, let’s roll up our sleeves and dive into the world of Node.js!
Setting up your project:
First create new directory by using manual steps. using terminal, Open your terminal or command prompt and navigate to the directory where you want to create your project. Use the mkdir
command to create a new directory for your project.
mkdir my-first-server
Initialize a new NodeJS project: Navigate into the newly created directory using cd
command and initialize a new Node.js project using npm (Node Package Manager) or yarn (alternative package manager for Node.js). Run one of the following commands:
cd my-first-server
npm init -y
This will create a package.json
file in your project directory with default settings.
Create server.js file in same folder and strat writing code
First lets import http module to create http server
const http = require('http');
Once we have our http
module imported, we'll define the hostname and port number for our server. These parameters will determine where our server will be accessible. For this example, we'll use the hostname 127.0.0.1
, which refers to the local machine, and port 3000
.
Now, let’s create our server using the createServer()
method provided by the http
module. This method takes a callback function as an argument, which will be invoked every time our server receives a request. Inside this callback function, we'll handle incoming requests and send back appropriate responses.
In our example code, we check the requested URL (req.url
) and HTTP method (req.method
) using the request object (req
). If the URL is '/'
, indicating the root path of our server, we respond with a simple HTML page welcoming visitors to our Node.js server.
If the URL is anything other than '/'
, we set the Content-Type
header to 'text/html'
and respond with a generic HTML page saying hello from our Node.js server.
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
const url = req.url;
const method = req.method;
if (url === '/') {
res.write('<html>');
res.write('<head><title>First NodeJs Server</title><head>');
res.write('<body><h1>This is first my first nodeJs Server</h1></body>');
res.write('</html>');
return res.end();
}
res.setHeader('Content-Type', 'text/html');
res.write('<html>');
res.write('<head><title>My First Page</title><head>');
res.write('<body><h1>Hello from my Node.js Server!</h1></body>');
res.write('</html>');
res.end();
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Check whether server is running or not:
To check whether the server is running or not, you can simply run your Node.js application from the terminal or command prompt. If there are no errors, and you see the console log message indicating that the server is running, then your server is indeed running successfully.
- Open your terminal or command prompt.
- Navigate to the directory where your
server.js
file is located. - Run the following command to start your Node.js server:
node server.js
- If everything is set up correctly, you should see the console log message indicating that the server is running, along with the hostname and port number (e.g.,
Server running at http://127.0.0.1:3000/
).
If you encounter any errors, carefully read the error messages displayed in the terminal or command prompt. Errors could be due to syntax issues in your code, missing dependencies, or port conflicts. Once you address any errors, you can try running your server again.
Additionally, you can open a web browser and navigate to the URL where your server is running (e.g., http://127.0.0.1:3000/
). If the server is running correctly, you should see the response generated by your server, such as the welcome message or HTML page you defined in your code.
Congratulations, Your Server Is Created!
Congratulations! You’ve successfully created your first Node.js server. By following along with this tutorial, you’ve learned how to set up a basic server using Node.js’s built-in http
module, handle incoming requests, and send responses back to clients. Whether you're a newcomer to web development or a seasoned developer exploring new technologies, building your own server is a significant milestone in your journey.
In our next blog post, we’ll delve deeper into server-side development with Node.js by exploring Express.js, a powerful and flexible web framework. With Express.js, you can streamline the process of building robust and feature-rich web applications, handling routes, middleware, and more with ease. Stay tuned for our next installment, where we’ll dive into the world of Express.js and discover how it can supercharge your server-side development experience.
Until then, keep experimenting, keep learning, and happy coding!