Create A Node.JS Server With Express From Scratch

Prerequisites

  • Node.Js [Download]
  • Knowledge of TypeScript / JavaScript

In this tutorial, we will be building a Node Web Server with the help of express (a web application framework built on top of node). Let's get started by creating a node application.

Crafting Our Application

To create a new node application, first create a new project directory, then type-in the following command inside of that directory.

λ npm init

After typing the above command, you will see the CLI is asking for some inputs like package name, version, description, entry point, test – right now you don’t need to enter anything there and you can skip all these by sending an additional flag -y in the command line, so our updated command will be as following –

npm init -y

Note: If you are using -y flag in CLI, you need to create your project directory without any space in between, for example node-app.

You will see a package.json file in your app directory which holds various metadata relevant to that project. That file provides information to npm (node package manager) about project dependencies, development dependencies, license information and many more.

Now, we need to install express framework to create a Server, to do that type-in the following command in your Terminal / Console.

λ npm install express --save

Structuring Our Folders / Files

Now, to serve files, we need to create a public directory from where the app will serve all the static resources like CSS, JavaScript, Images, Icons and HTML files. So our updated folder will look like this –

Creating Our Server

Now with all these set and done, let's do the coding part, copy the following code in the index.js

In this code snippet I used port = 5000. You can use any port number here. If its not mentioned, system will use an arbitrary port for the application.

Running Our Application

To run our newly created application, we need to start the server, to do so write this command in your Terminal / Console.

λ node index.js

If everything goes right, you will see a message in your console saying "node-server app listening on port 5000"

Now, open 127.0.0.1:5000 from your Browser. If you have some content in your index.html file then you will be able to see it in your browser.

In this case, I wrote a few lines in my index.html page and added some other files as well. You can find my version of this application at the bottom of this post.

Lot of things can be done using express and node, feel free to browse express.js documentation to learn more.

You can download this complete tutorial from my GitHub Repository

Copy link
Powered by Social Snap