Setting Up a Basic Node.js Server
Introduction and Topic Overview
Hi! Today we are going to dive into an exciting new topic: Setting up a basic Node.js server. So, the first question that may come to your mind could be — why would we need a server, and what does Node.js have to do with it?
Think of servers as the friendly librarians of the internet. Whenever you need a book (web page), you request it from your librarian (server), and it fetches the book for you. Now, Node.js, as a powerful JavaScript runtime, allows JavaScript to serve as our friendly librarian, handling thousands of requests in a fast, efficient manner.
Our goal today is simple: by the end of this lesson, you will be able to set up and run your own basic server using Node.js. Isn't that exciting? Let's get started!
Understanding Node.js
Node.js is a JavaScript runtime, which means it lets us run JavaScript on our computers, which was previously possible only in a web browser. What makes Node.js elegant is its event-driven, non-blocking I/O model, which makes it efficient for building fast and scalable server-side applications. So, what does this mean? In simple terms, this model allows Node.js to handle many tasks simultaneously without waiting for another task to complete, which is extremely useful for real-time applications.
Let's imagine a food delivery application. As there can be many orders coming in at the same time, the event-driven model of Node.js enables the application to simultaneously process these requests without making the users wait for each order to be processed one after the other.
Introduction to Express.js Framework
Meet Express.js, which is a very popular and minimalist framework for Node.js. Why do we need this when we have Node.js? Well, if Node.js is a raw ingredient, Express.js is a method to cook it into an easy-to-consume dish.
Express.js streamlines the server creation process that is already feasible with bare Node.js. It adds various features to our Node.js, like handling multiple routes with a single line of code and middleware for managing requests.
Getting Started with Node.js and Express.js
Before you can start setting up your server, there are a couple of things you need to ensure. You should have Node.js installed on your computer to run a server. You also need Express.js, which can be installed using npm (Node Package Manager). However, on CodeSignal, all these come pre-installed, so you don't need to worry about installation.
Let me show you a little code snippet on how to create an Express application instance and how to make it listen for connections on a specific port.
When we run this code in Node.js, it starts a server on port 3000 of your computer. You might wonder what require('express') is doing. It's simply importing the express module.
