Create a simple server application with Node.js and Express
So you keep hearing about Node.js and how easy it is to build server-side applications and web services with it, and you want to try it out but don't know where to start yet. This article could be your entrance to Node.js and building APIs and server applications with it!
We will be using a web framework for Node.js called Express.js (or just Express) to demonstrate how to create a web server in just 9 lines of code!
But before that, let us discuss what we know about Node and Express.
What is Node.js?
What is Express?
If you don't have Node.js installed on your computer, you can go to this link and set it up.
If you have finished installing Node.js, you should be able to go to your terminal / command prompt and run node command.
Now, create a project folder named 'ServerDemo' (or anything, I just use ServerDemo for this article). Inside the project folder, run the command: npm init
Then, fill in the details for the application. Here's a screenshot of mine.
This creates a package.json file at the root of our folder.
Since I have specified server.js as the entry point of my app, I will start by creating a file with the same name.
Now, go to your terminal and run the command: npm install express
What this does is, it installs Express in our project and lists it as one of the dependencies in the package.json file.
Create a server
Now that we have installed everything we need, let's start writing code.
In the server.js file,
This piece of code imports the just installed 'express' module into our server.js file.
Then, we create an Express application by calling the top-level express() function, that is exported by the express module.
We also specify a port for our server to listen on.
This section of our code handles the requests to the server and is responsible for sending out responses.
This function handles any GET requests to the route '/' (it is the default or main route for our server).
The middleware function takes two parameters, a request object and a response object.
When we receive a GET request, we send a 'Hello World!' message as a response.
Our server will listen on the port 3000 we specified previously. When the application starts listening, the callback function will be invoked so that we will know.
The full program,
Run the server
To run our sever, from the root of the project folder, run the command: node server.js
Then, you should be able to open up a browser and see what you just did! Just visit localhost:3000 for confirmation.
You've just created a Node.js application and successfully run it!
If you'd like to learn more on building REST APIs with TypeScript and Node.js, here's a really descriptive article on exactly that. The article even touches on the fundamentals of Object-Oriented Programming with TypeScript!