NodeJS Basic Server
Tags: node, javascript, tutorial
Published: 2020-09-10 21:59:41

<!-- wp:paragraph -->
<p>If you spend too much time thinking about a thing, you’ll never get it done.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>–&nbsp;<em>Bruce Lee</em></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In today's article we will be figuring out how to build a basic server using <a rel="noreferrer noopener" href="https://nodejs.org/en/" target="_blank">nodejs</a>. Assuming that you have some basic understanding on <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript" target="_blank">javascript</a> and <a rel="noreferrer noopener" href="https://www.npmjs.com/" target="_blank">npm</a>. Overview on what node.js can do and what it can do. Later on we will move onto the <a rel="noreferrer noopener" href="http://expressjs.com/" target="_blank">Express</a> framework.  This article will be split into a small segments to help break down our understanding.  We will be using javascript ES6. </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"align":"center","level":3} -->
<h3 class="has-text-align-center">Topics</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Node.js introduction</li><li>Node.js Server</li><li>Testing server locally</li></ul>
<!-- /wp:list -->

<!-- wp:quote -->
<blockquote class="wp-block-quote"><p>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.</p><cite>Stephen Hawking</cite></blockquote>
<!-- /wp:quote -->

<!-- wp:heading {"align":"center"} -->
<h2 class="has-text-align-center">NodeJs intro</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>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. <br><br><strong>Why build a server using Nodejs and not something like python or php?<br></strong> We have some advantages for using nodejs over other languages, we eliminate multiple threading, take advantage of <strong>asynchronous</strong> since node will run on a single thread, and the huge ecosystem that is supported by the community NPM (node package management).</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>Are there disadvantages?</strong><br>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, <strong> </strong>javascript sometimes isn't always the best solution for the job when thinking about servers.<br><br>Enough about learning why we use nodejs, lets get into the coding. </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"align":"center"} -->
<h2 class="has-text-align-center">NodeJS Server</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>We will begin writing our simple <strong>NodeJS server</strong>. Start off by having an empty folder, you can name it what ever you like. </p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":144,"width":541,"height":173,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large is-resized"><img src="https://smartoscar.files.wordpress.com/2020/09/screen-shot-2020-09-06-at-4.17.18-pm.png?w=379" alt="" class="wp-image-144" width="541" height="173"/><figcaption>Empty folder</figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Next create a <code>&lt;fileName.js&gt;</code> file. In this file we will write out our node.js server code. </p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":146,"width":537,"height":158,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large is-resized"><img src="https://smartoscar.files.wordpress.com/2020/09/screen-shot-2020-09-06-at-4.19.25-pm.png?w=381" alt="" class="wp-image-146" width="537" height="158"/><figcaption>javascript file</figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>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. <br></p>
<!-- /wp:paragraph -->

<!-- wp:heading {"align":"center","level":5} -->
<h5 class="has-text-align-center">Code Example</h5>
<!-- /wp:heading -->

<!-- wp:image {"id":150,"width":605,"height":312,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large is-resized"><img src="https://smartoscar.files.wordpress.com/2020/09/screen-shot-2020-09-07-at-12.23.41-am.png?w=676" alt="" class="wp-image-150" width="605" height="312"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>The first line of code is allowing us to obtain the tools from the <code>http</code> module that is provided by node.js. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center"><code>const http = require('http');</code> <br>we store our module into an http <strong>variable</strong> to help us use it easier through our code.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center">The <strong>hostname</strong> &amp; <strong>port</strong> variables store two important things, hostname stores our computers ip address as a <strong>string</strong>, we can set it at zero and the computer will do it automatically, but do which ever you prefer.<br><code>const hostname = '127.0.0.1';</code></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center"> <strong>Port</strong> 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. <br><code>const port = 3000</code></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>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 <strong>variable</strong>, we can simply call it <strong>server</strong>. This is where we will now be taking advantage of our nodejs <strong>http module</strong>. <br>                                        <code>const server = http.createServer()</code></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now within our <code>createServer()</code> method we want to get some type of information back when connecting to the server. What we want to do is add a <strong>callback</strong> with two arguments, <strong>request &amp; response</strong> short for req &amp; res.  Which will look like this. <br>                                   <code>http.createServer( ( req, res) =&gt; {})</code><br><strong><br>So what exactly is going on here?</strong><br><code>createServer()</code> method is one of the tools that we will commonly use to create a server. We store it in a <strong>Server</strong> variable to help us track our http method in one location.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"align":"center","level":5} -->
<h5 class="has-text-align-center">Code Example</h5>
<!-- /wp:heading -->

<!-- wp:image {"id":153,"width":567,"height":218,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large is-resized"><img src="https://smartoscar.files.wordpress.com/2020/09/screen-shot-2020-09-07-at-12.37.16-am.png?w=499" alt="" class="wp-image-153" width="567" height="218"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center">So far our code should look like the image above. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Next we want to get some type of <strong>response</strong> 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 <strong>properties &amp; methods</strong> to allow us to communicate with the web browser.  </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><code>const server = http.createServer( ( req, res) =&gt; {</code><br>  <code>   res.statusCode = 200;<br>    res.setHeader('Content-type', 'text/plain')<br>    res.end('okay');</code><br><code>})</code></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>So what is going on here now? <br></strong><code>res.statusCode = 200;</code> , this property controls the status code that is sent back to the client when the headers get flushed. <br><code>res.setHeader('Content-Type', 'text/plain')</code>, we are simply adding a singular header, later on in the future we can add multiple headers at once using a different method.<br><code>res.end('okay')</code>,  this method pretty much sends a signal to the server notifying it that all the headers and body have been sent. <strong>Must be called on each response. </strong><br><br>We are almost finished with our basic node.js server!</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"align":"center","level":5} -->
<h5 class="has-text-align-center">Code Example</h5>
<!-- /wp:heading -->

<!-- wp:image {"id":156,"width":624,"height":256,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large is-resized"><img src="https://smartoscar.files.wordpress.com/2020/09/screen-shot-2020-09-07-at-12.55.39-am.png?w=584" alt="" class="wp-image-156" width="624" height="256"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Finally, we just need to have our server listening for a connection.  We will do this by using the <code>listen()</code> method on our <strong>server</strong> variable. As following<code> server.listen()</code>.<br>Inside the <code>listen</code> method we will pass in our arguments that we want to assign, which are <strong>hostname </strong> &amp; <strong>port</strong>, also we want to add a <strong>callback</strong> function to help us see where our server is being connected to. Now our code should look like this. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center"><code>server.listen(port, hostname, () =&gt;{ })</code></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Last but not least, now that we have our <strong>server</strong> listening to a connection we can add a <strong>console.log()</strong> inside our call back to display our server location for the human eye to see. Our final code should look like the code below. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><code>server.listen(port, hostname, ( ) =&gt; {</code><br><code>    console.log(Server running at http://${hostname}:{port}/`)</code><br><code>})</code></p>
<!-- /wp:paragraph -->

<!-- wp:heading {"align":"center"} -->
<h2 class="has-text-align-center">Final Code </h2>
<!-- /wp:heading -->

<!-- wp:image {"id":166,"width":727,"height":376,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large is-resized"><img src="https://smartoscar.files.wordpress.com/2020/09/screen-shot-2020-09-07-at-12.23.41-am-1.png?w=676" alt="" class="wp-image-166" width="727" height="376"/></figure>
<!-- /wp:image -->

<!-- wp:quote -->
<blockquote class="wp-block-quote"><p>If each dead person became a ghost, there'd be more than 100-billion of them haunting us all. Creepy, but cool</p><cite>Neil deGrasse Tyson</cite></blockquote>
<!-- /wp:quote -->

<!-- wp:heading {"align":"center"} -->
<h2 class="has-text-align-center">Testing Server Locally</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>NOW WE ARE ALMOST DONE!! One last thing is to make sure our code is working! Lets head over into our <strong>terminal</strong>, once you are in your directory with the <strong>index.js</strong> file, in your command line run <code>node index.js</code>. 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 <strong>Okay</strong> text response. <br><br>CONGRATS! You have now created your own node.js server using simple node.js <strong>http</strong> module with its properties and methods.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"align":"center","level":4} -->
<h4 class="has-text-align-center">Conclusion</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>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. <br></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>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!</p>
<!-- /wp:paragraph -->