If you spend too much time thinking about a thing, you’ll never get it done.
– Bruce Lee
In today's article we will be figuring out how to build a basic server using nodejs. Assuming that you have some basic understanding on javascript and npm. Overview on what node.js can do and what it can do. Later on we will move onto the Express framework. This article will be split into a small segments to help break down our understanding. We will be using javascript ES6.
Topics
- Node.js introduction
- Node.js Server
- Testing server locally
We are just an advanced breed of monkeys on a minor planet of a very average star. But we can understand the Universe. That makes us something very special.
Stephen Hawking
NodeJs intro
Nodejs has allowed javascript developers to adapt to new possibilities. Like being allowed to create command line utilities, networking software, web services, web applications, and etc. With nodejs we can use javascript to develop software that was only written using other languages. Today we will write out our own server with nodejs code, mostly for web services that connect with clients using JSON format for data interchange.
Why build a server using Nodejs and not something like python or php?
We have some advantages for using nodejs over other languages, we eliminate multiple threading, take advantage of asynchronous since node will run on a single thread, and the huge ecosystem that is supported by the community NPM (node package management).
Are there disadvantages?
Yes, there are disadvantages to using nodejs, mostly like single-threaded can't work with servers with multiple cores, npm does have repetitive software so it can be hard to find the right one for your work at times, javascript sometimes isn't always the best solution for the job when thinking about servers.
Enough about learning why we use nodejs, lets get into the coding.
NodeJS Server
We will begin writing our simple NodeJS server. Start off by having an empty folder, you can name it what ever you like.
Next create a <fileName.js>
file. In this file we will write out our node.js server code.
The code below shows how our server will look at the end, we will go through each line and figure out what is going on.
Code Example
The first line of code is allowing us to obtain the tools from the http
module that is provided by node.js.
const http = require('http');
we store our module into an http variable to help us use it easier through our code.
The hostname & port variables store two important things, hostname stores our computers ip address as a string, we can set it at zero and the computer will do it automatically, but do which ever you prefer.const hostname = '127.0.0.1';
Port is the remote server number, you can simply put this as any number as long as you don't have duplicate servers running on the same port. const port = 3000
Now that we have our basic set up, let's create our server now. We want to do this by simply storing our server into a variable, we can simply call it server. This is where we will now be taking advantage of our nodejs http module.
const server = http.createServer()
Now within our createServer()
method we want to get some type of information back when connecting to the server. What we want to do is add a callback with two arguments, request & response short for req & res. Which will look like this.
http.createServer( ( req, res) => {})
So what exactly is going on here?createServer()
method is one of the tools that we will commonly use to create a server. We store it in a Server variable to help us track our http method in one location.
Code Example
So far our code should look like the image above.
Next we want to get some type of response back, for now we will only dig into our response argument as it will take a bit long for this article to get through everything. We will learn more about the request argument in a later article. Now we will want to use built-in properties & methods to allow us to communicate with the web browser.
const server = http.createServer( ( req, res) => {
res.statusCode = 200;
res.setHeader('Content-type', 'text/plain')
res.end('okay');})
So what is going on here now? res.statusCode = 200;
, this property controls the status code that is sent back to the client when the headers get flushed. res.setHeader('Content-Type', 'text/plain')
, we are simply adding a singular header, later on in the future we can add multiple headers at once using a different method.res.end('okay')
, this method pretty much sends a signal to the server notifying it that all the headers and body have been sent. Must be called on each response.
We are almost finished with our basic node.js server!
Code Example
Finally, we just need to have our server listening for a connection. We will do this by using the listen()
method on our server variable. As following server.listen()
.
Inside the listen
method we will pass in our arguments that we want to assign, which are hostname & port, also we want to add a callback function to help us see where our server is being connected to. Now our code should look like this.
server.listen(port, hostname, () =>{ })
Last but not least, now that we have our server listening to a connection we can add a console.log() inside our call back to display our server location for the human eye to see. Our final code should look like the code below.
server.listen(port, hostname, ( ) => {
console.log(Server running at http://${hostname}:{port}/`)
})
Final Code
If each dead person became a ghost, there'd be more than 100-billion of them haunting us all. Creepy, but cool
Neil deGrasse Tyson
Testing Server Locally
NOW WE ARE ALMOST DONE!! One last thing is to make sure our code is working! Lets head over into our terminal, once you are in your directory with the index.js file, in your command line run node index.js
. Then you should see your server get console logged onto the terminal. Head on over to the server link! And you should successfully see an Okay text response.
CONGRATS! You have now created your own node.js server using simple node.js http module with its properties and methods.
Conclusion
I hope by the end of this article you managed to learn how to create and understood what is going on in every line of code. It is very important to understand how your code fully works, not only does it help you become a better developer but can also help you use the tools you are working with more efficient.
These articles are mostly intended for personal use on becoming a better programmer, writer, and grow my programming skills. Feel free to drop any feedback or corrections that you believe that should be made to help me and others. Thank you for your time for sticking this far!
Top comments (0)