Intro to Node.js

2948 VIEWS

Let’s be honest—You’ve probably been hearing a lot about Node.js, but you still have no idea what it is or what it’s used for. Perhaps you’ve been dealing with other backend technologies and want to familiarize yourself with Node.js to learn what it offers and how it differs from other backend technologies. If you fall within these categories, then I encourage you to keep reading. (If you don’t, you are still encouraged to keep reading.)

What is Node.js?

Node.js is an event-based, non-blocking, asynchronous I/O framework built on Chrome’s V8 JavaScript engine.

This definition is a lot to take in at once. Let’s break it down and see if we can get a better understanding. Let’s start with the term “event-based.” This simply means each transaction that occurs is a reaction to an event.

Secondly, we have the term “non-blocking.” This means Node.js code does not block another piece of code from executing—In other words, an operation can be executed while another operation is executing. Blocking typically refers to operations that block further execution until that operation finishes.

Next, there’s “asynchronous.” Asynchronous execution refers to the execution that does not run in the sequence in which it appears in the code.

Hopefully you now have a better understanding of what Node.js is. The important question at this point is, “What is it used for?” Well, Node.js is used to build powerful, fast and scalable web applications.

Features of Node.js

It is extremely fast: Node.js is built on Google Chrome’s V8 JavaScript Engine—Therefore, it is very fast in code execution.

Single-threaded: Node.js follows a single-threaded model with event looping, which means Node.js can easily handle concurrent client requests without creating more and more threads because of the event loop. Furthermore, less threads mean that Node.js utilizes less resources.

It’s asynchronous and event-driven: What this means is that Node.js-based servers do not wait for an Application Programming Interface (API) to return data.

What can Node.js do?

  1. Node.js can create, open, write, read, delete, and close files on the server.
  2. Node.js can generate dynamic page content.
  3. Node.js can collect form data.
  4. Node.js can add, delete, and modify data in a database.

What can we build with Node.js?

  • REST APIs and backend applications
  • Social applications, blogs
  • Real-time services (chat, apps, games, etc.)
  • Anything that is not CPU-intensive
  • Node.js will need to be installed, so you may download the setup from the website and run the executable file. Once it’s done installing, you can open Node.js with Command Prompt on Windows or the Terminal on Mac and type the following command to see the version ‘node –version’.

    You’re probably wondering if you’ll be typing your code in the terminal—Well, no. There are several editors you may download. Some examples are Sublime, Atom, Visual Studio Code, etc. The following example shows how to run a Node.js file using Command Prompt.

     
    //app.js
    console.log("Hello World");
    

    Note: app.js is a file saved on the desktop; therefore, we need to move to the desktop.
    To run the file, we simply type ‘node filename’, and as we can see in Command Prompt, it has printed “Hello World.”

    Modules

    Simply put, every file in a Node.js project is a module. These modules may contain some functionality that may be reused throughout the Node.js application. We can create our own modules, as well as use modules created by other developers.

    In this section, we’ll cover two key concepts: require and module.exports.

    1. require allows you to include modules in your programs. You can include built-in core Node.js modules, community-based modules and local modules.

    While there are probably hundreds of modules, we’ll consider two core built-in modules. To work with the filesystem, Node.js has a core module named ‘fs’. To handle http requests, Node has a core module named ‘http’.

     
    const fs = require('fs');
    const http = require('http');
    

    2. module.exports allows you to export your own objects and functions.
    To begin, let’s create two files. The main module should be named ‘app.js’, while the second is called ‘logger.js’. In the logger.js file, let’s create a simple function called ‘greetings’, which prints “Hello World.” Then we’ll export it and make use of it in the app.js file.

     
    //logger.js
     
    function greetings(){
            	console.log('Hello Frederick');
    }
     
    //module.exports.name=function or object name
    module.exports.greetings = greetings;
    

    Back in the main module, we can include the logger module by using the require method.

     
    //use ‘./’ to point to the same directory
    const logger = require('./logger.js');
     
    //this should print Hello Frederick
    logger.greetings();
    

    Working with some of the core built-in modules

    In this section, we’ll take a look at how we can make use of the ‘fs’ and ‘http’ modules to create a basic web server and read files.

    The http module can be used for creating networking apps. This example will create a basic web server that listens for http requests at a given port.

    You can execute the following code using Command Prompt and open a browser to navigate to ‘localhost:3000’. The page should print “Hello.” Furthermore, if you navigate to ‘localhost:3000/courses’, you should see an object of courses.

    Note that each time you make a change and save your files, you may need to terminate the program in Command Prompt using ‘ctrl-c’, then execute it again.

     
    //include the module
    const http = require('http');
     
    //any given port number
    const port = 3000;
     
    //create a server
    //parameters – request and result
    const server = http.createServer(function(req, res){
    if(req.url==='/'){
                        	res.statusCode=200;// description -OK
                        	res.write("hello")
                        	res.end()//end the response process
            	}
     
            	if(req.url==='/courses'){
                        	res.statusCode=200
                        	//convert this into a string
                        	res.write(JSON.stringify(["Mathematics", "English", "Biology"]))
                        	res.end()
            	}
    });
     
    //create a listener on the given port
    server.listen(port, function(){
            	console.log("listening on port 3000...")
    });
     
    

    The fs module allows you to work with the file system on your computer. The following example will demonstrate how we can use the http and fs modules to read a file and display it in the browser.

    Let’s start by creating a simple HTML file named index.html.

     
    
    
    

    Hello World

    Now, in the app.js file, type the following code to create a server and read the file.

     
    //app.js
    const http = require('http');
    const fs = require('fs');
     
    const port = 3000;
     
    const server = http.createServer(function(req, res){
            	fs.readFile('index.html', function(err, data){
                        	res.writeHead(200, {'Content-Type': 'text/html'});//status code 200 means all is OK, the second argument is an object containing the response headers
                        	res.write(data);
                        	res.end();
            	});
    })
     
    server.listen(port, function(){
            	console.log("listening on port 3000...")
    });
     
    

    Congratulations! You now have a better understanding of Node.js, and you have been introduced to some of the key modules. To learn more about the core modules, you can check out the documentation.


    Frederick Plange is a computer science major at Ashesi University, one of the top universities in Ghana aiming to develop ethical and entrepreneurial leaders to transform the nation. Frederick is a focused and goal driven individual that is passionate about technology and computers


    Discussion

    Click on a tab to select how you'd like to leave your comment

    Leave a Comment

    Your email address will not be published. Required fields are marked *

    Menu
    Skip to toolbar