Node.js: Setting up a Server π β‘π
Introduction
Everyone has a moment in their coding career where they realize they generally enjoy programming. We all have our own cherished experiences making for great anecdotes in super cool social settings. For me, one of these experiences was linking my back-end server(Ruby on rails π π π ) with my front-end javascript(π π π ) client. It was one of the most satisfying and self-validating things I had done so far. This βDr. Frankenstein-sequeβ experience was like electricity! I was inspired to build more, optimize more, and add more features! π
Today in this blog, Iβll be covering how to set up a server with vanilla Node.js. I will go through each step and explain how things work. Hopefully, this under the hood approach will help frame up your understanding for even more complex concepts and abstractions using Node.js. Setting up a Server is a fundamental building block, so spend time on the concept is really key π to understanding why things work. It will pay off down the line when you dive into choosing a Web-framework like Express.js(popular).
Letβs dig in! π³ π π¦‘
Installing Node.js
Link to Super Cool Node.js Blog π πͺ π§:https://ineedmoreplates.medium.com/learning-node-js-8288e0411957
In case you havenβt been keeping up with all my blogs. I wrote a nice blog + setup guide for installing Node.js. I highly encourage you to give it a read. It explains Node.js in more detail. You get an easy-to-follow step-by-step guide on how to install Node.js(towards the bottom).
Letβs talk about Setup :
In case you forget:User/Client(Browser): Think of what's on your Device. Example: "Safari", "Chrome","Mozilla", etc.URL: Think of this an encoded and human-readable address. Well all use it when typing in a web address on our browsers. Domain: an identification string that defines a realm of administrative autonomy, authority or control within the Internet.Request: The Domain sends a request to the server with an IP address belonging to that Domain.IP address: unique ID used to identify each device on a Domain(DNS).Server: Hardware, We will be writing our code for it.
Before we start writing any code, letβs quickly review how a web page works. Imagine a User types in a URL address. Letβs say itβs something pretty common, like googling cat videos π , read a tech blog π€ , buy a cast iron-pot on Amazon π₯ ! Whatβs happening?
Yup, itβs Meta, but hear me out. This will bring additional understanding with each keystroke we take. Itβs easy to remember patterns in coding, but the skill lies in understanding and conveying what the heck we just did?
User types in URL for a Webpage:
- User hops on a browser
- The User enters in a URL
- URL is passed to a Domain
- Domain sends a request to a server (HTTP)
- The Server receives the request
- If everything passes, the Server grabs data from the Database
- The Server returns a response ( HTTP page)
Wow, there are a few steps, then you realize, huh? There are even more when we talk about log-in, cookies, security, etc. The idea is we want a basic understanding here.
Since Node.js is a back-end run-time for Javascript will be writing our code to the Server(Back-end)itself. In this list, that would be step 5.
Judging by this list, we can expect to deal with Incoming requests, Outgoing responses, and some communication with a Database. We also know what will be sending back to the User will be an HTTP page.
Just a friend reminder: HTTP and HTTPSHTTP: Hyper Text Transfer Protocol, it's a Protocol or way of transfering Data which your Browser or Server can understand.HTTPS: π Hyper Text Tranfer Protocol Secure, It's HTTP + Data Encrpytion during Transmission. Way more secure, great for online banks, E-trading, etc. ! (look at the π icon next to your URL, that's HTTPS π )
Letβs Build π¨ π§° π :
Today Iβm building with :1. OS operating system(if not, just keep reading) π π π 2. Vscode π€ πΉ π 3. Node.js π©βπ¬ π¨βπ¬ π§βπ¬4. Basic Understanding of Javascript π πͺΆ π
Pre-steps:
- Letβs start by creating a new folder in our file directory. You can name it whatever you like. I prefer something short and easy to recognize.
2. Letβs open up our code editor. Iβm a Vscode junkie. Feel free to use whatever you like.
3. Letβs open a terminal and navigate our way to the create folder
Step-by-Step:
Now that we are all setup. Letβs dive into some step-by-step coding -paired with some helpful explanations. Donβt be afraid to test things out on your own. Itβs the best way to understand things work.
Step 1: letβs create a file called app.js. This will be creating our server here.
Step 2: We Will be importing a baked-in Core Module found in Node.js.
Looks like this:const http = require('http'); <-- This is a global scope
*** require(), Node.js syntax for importing, it takes a string argument
Step 3: The HTTP Module has a fair selection of methods. Will be using the .createServer() method.
Looks like this: const http = require('http') <-- importhttp.createServer(); <-- access method, JS style
Step4: .createServer() is a special function that takes a function as an argument. This function needs to take 2 arguments as a response and a request. We can also name this function and its arguments whatever we want. Yet Iβm a huge fan of arrow syntax + anonymous functions. Itβs worth looking into as itβs easier to read and cuts down on writing code. Check out my example below.
const http = require('http')http.createServer((req,res) => {}); <-- clean & easy to readres = response
req = request
Step5: .createServer() as the name implies outputs a server. Will save that to a const variable and have our function return a response.
const http = require('http')const server = http.createServer((req,res) => {console.log(res) <-- let's just console.log for now π}); <-- clean & easy to read
Step6: Letβs find a Port π’ . We will be listening for our Server variable. This method will listen for a port address. Letβs plug in the standard 3000 as an argument. Will also return a console.log of the res argument.
const http = require('http')const server = http.createServer((req,res) => {console.log(res) <-- let's just console.log for now π});server.listen(3000); π§ββοΈ "Hello, hey!!!"
Step7: In our terminal will run our file named app.js. Your server should spin up. Note the blinking cursor. If you need to end, the server uses the shortcut βCtrl + cβ to end the server.
Looks like this:node app.js <-- ctrl + c kills server!
Step8: Letβs run our Server and open up a browser. After that will move back to our terminal and take a peek. You should see some new activity in your terminal.
localhost: 3000 <-- type in URL field of your browser!
Conclusion
Congrats! π Youβve deployed your first Server on Node.js. Can you feel that inspirational energy! Now go build something cool! The power of a javascript run-time environment is yours to command. If you liked this blog, donβt be afraid to give me some claps. Happy Coding all π πΉ π!
Links:
Great Course on Node.js: https://www.udemy.com/course/nodejs-the-complete-guide/My Node.js: https://ineedmoreplates.medium.com/learning-node-js-8288e0411957Require function: https://nodejs.org/en/knowledge/getting-started/what-is-require/Create server method: https://www.w3schools.com/nodejs/met_http_createserver.aspListen method: https://www.w3schools.com/nodejs/met_server_listen.asp