1454 views 0 comments

Hands on with Node.js | HTTP Server – Hello, World!

by on October 21, 2015
 

Update[21 Oct 2015]: Added Express module to host static files on your HTTP server.


So, today I was exploring some unknown waters while surfing the web about setting up a web-app on a local server. I have had created my share of LAMP & WAMP stacks. I was just exploring and read about how we can use Node.js to basically setup a server in less than 5 lines of code. Hmm interesting right? So, I dived deep into the same and would like to share my learnings.

I will consider myself a 5/10 in Pure JavaScript and have had written few quick dirty scripts to scrap data of webpages. I have also used JQuery on many occasions to customize the functionality of HTML5 component, but sadly, I never had a chance to explore much about JS popular frameworks.

Before we start, let’s understand some basics:

What is Node.js?

Well, as per Node.js website, it can be explained as:

Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js’ package ecosystem, npm, is the largest ecosystem of open source libraries in the world.

Gibberish? Ha! Let me make it super easy for you. Node.js is javascript based runtime environment which can be used to develop Input/Output intensive web applications like video streaming sites, single-page applications, and other web applications. Node.js is open source, completely free, and used by thousands of developers around the world. It basically allows to have freedom to use JavaScript on both client & server side. Ain’t that awesome?

💡 Read about the interesting history of Node.js to know the story behind it’s evolution.

Why should I use it?

Ahan! Now that’s a real question. Node.js shines in real-time web applications employing push technology over websockets. What is so revolutionary about that? Well, after over 20 years of stateless-web based on the stateless request-response paradigm, we finally have web applications with real-time, two-way connections, where both the client and server can initiate communication, allowing them to exchange data freely. This is in stark contrast to the typical web response paradigm, where the client always initiates communication. Also, it’s all based on the open web stack (HTML, CSS and JS) running over the standard port 80.

Some key points:

  • Its lightweight, efficient
  • Node.js is asynchronous, a non-blocking IO model
  • JavaScript everywhere, you do not need to worry about developing backend in non JavaScript language(example: Java/.Net/PHP/Python/Ruby etc). Node.js lets you write JavaScript code on server side, which again supports all the popular DB Engines(example MongoDB, MySQL etc).
  • Node.js applications are super fast as compared to other technologies

Awesome! What do I need?

  1. Duh. Download Node.js
  2. Download Git Bash. Always a good practise to push your code.
    git scm install node.js

    Make sure these are checked

  3. Some basic understanding of JavaScript
  4. Good knowledge of HTML, CSS, AJAX will speed things up for your next awesomest webapp.

Ready, Set, Go!

Verify Node.js installation!

Create a js file named main.js on your machine (Windows or Linux) having the following code.

Now, fire up command prompt or git bash in that directory and execute main.js file using Node.js by command:

$ node main.js

If everything is fine with your installation, this should produce the following result:

Check!

Few steps to set up Node:

  1. Create a new folder in your file system. This would act as a base for your project.
  2. Open your project folder, right click in the window and select Git Bash Here. Enter npm and press enter. You should see something like this:
    npm installation verification

    Node package manager is up!

    💡 npm is a package manager for JavaScript, and is used as default for Node.js.

  3. Type npm init in the same terminal window and it will ask you to go through a series of steps.
    Make sure to work your way through it, input what’s necessary and just leave blank and press enter on whatever you don’t understand. Something like this:
npm init to create a package json file node.js

Fill em up.

  • Step #3 will create a package.json file in your project directory. Try opening the file using your favourite text editor and you will see a JS object with all the dependencies and app information.
    💡 I use Adobe Brackets as my default text editor. It is awesome! Go ahead & try it out! 😀
  • Now, create a new empty text file with the name app.js in your project root folder.

Hello, World?

Well, this is kind of customary so let’s get over with it. We will go through the basic node.js “Hello World” program and some in-house APIs to get a clear understanding.

Disclaimer: While HTTP is not the only use case for node.JS, most people are using it as a web application platform. So the next example will be a simple HTTP server that responds to every request with the plain text message “Hello World”.

  1. Fire up your text editor and open app.js file. Now we are ready to do some code mc’lovin!
  2. This is the code. I will explain how it works.
  3. Save the file. Go to your project directory. Open Git Bash here and use command node app.js to execute the above piece of code. You will have a screen like this:
    node app first run

    😎

    💡 You may get a Windows security alert because here node will be serving the app.js snippet on port 9999. Make sure to allow access.

  4. Open your browser and go to url: http://localhost:9999 and TaDa! “Hello, World!”

    first hello world app node js

    Hello, World!

Now, before we move into more sorcery, let’s break down the code snippet above and understand how it works?

Hello, World – EXPLAINED!

  • This will load up the http module to create an http connection which we will be using to create an HTTP server in next step.

  • Here we are configuring our HTTP server to respond with Hello World to all requests when the connection is made with http status 200 between client and server. The createServer() function here takes two arguments request and response.
  • response.writeHead() sends response header to the request which includes content-type and other useful options.
  • response.end() notifies the server that all of the headers and body have been sent, and the request and response are handled(completed).

  • Now since we have created an Instance of http server, it’s time to start it up. The http server will listen on port 9999 and the IP will be the defualt localhost or 127.0.0.1 
  • This means every time someone will try to access localhost:9999, server will serve our “Hello, World!” string to the client in plain text format and console.log will log the statement inside to the console on server end.

💡 Make sure to do a response.end() else you will see a continuously loading page, because the Node.js server treats the res.end() is the signal for response sent successfully, if we miss this, Node.js treats that the server is still processing the response and it waits for it to end.

When I say basic, I mean basic. This is not a full-featured HTTP server. It can’t serve any HTML file or images. In fact, no matter what you request, it will return ‘Hello World‘.


Express

Fast, unopinionated, minimalist web framework for Node.js

Well, somebody asked me that what if we want to host HTML files on our HTTP web server instead of writing in js or maybe even resources like Images, Videos etc. So, here we are! Express is a framework that makes creating most normal websites very simple. The first thing you have to do it install it. Fire up your cmd/bash shell in your project directory and type:

$ npm install express

When you install a module, it will put it in a node_modules folder inside your application directory. You can now require it like any built-in module. Let’s create a basic static file server using Express.

and to start it off, just key in:

$ node my_static_file_server.js

TaDa. You now have a pretty capable static file server. Anything you put in the /public folder can now be requested by your browser and displayed. HTML, images, almost anything. So for example, if you put an image called “awesomePic.jpg” inside the public folder, you can access it using your browser by going to http://localhost:8080/awesomePic.jpg.

Joker on node.js

What? I told you it’s an awesomePic 😉

Of course Express has many more bells and whistles to it but I will leave that on you to explore. 😉

Pro Tip: Use the knowledge above to create a kickass file server on your Raspberry Pi and use the connected External HDD as the directory path. Congrats. You got yourself a NAS (Network attached storage) 😉


Let’s stop here. The motive of the post was to get you and me started with Node.js. I surely will start experimenting with Node.js in my free time and may add few interesting modules in this post later. You can see how easy it is to setup an HTTP server here. Now it’s all about how created you can get. 😉

Let me know if you start with something. Good luck.

Be the first to comment!
 
Leave a reply »

 

Leave a Response