* * *

This article will brief you about what Node.js is, why it is used, and how to write simple programs in Node.js.

Node.js is a Javascript runtime environment which lets you execute javascript code outside of a browser(on the V8 Javascript engine).

For a very long time, PHP had unanimously dominated the server side scripting industry. So what exactly made Node.js so popular that it has become the most popularly used framework/tool in today's development world(https://insights.stackoverflow.com/survey/2019#technology-_-other-frameworks-libraries-and-tools)?

Node.js offers some really cool features like asynchronous nature, event driven, non blocking I/O, efficient single threaded model etc.. While we will discuss about the asynchronous nature of Node.js, you may read this article: https://www.tutorialspoint.com/nodejs/nodejs_introduction.htm and watch this video: https://www.youtube.com/watch?v=jOupHNvDIq8 to get a clear understanding of these features of Node.js and how it works.

You can download Node.js from their official website(https://nodejs.org/en/download/).
You can also follow these videos:-
1. Windows : https://www.youtube.com/watch?v=gHuIKptS0Qg (until 4:30)
2. Ubuntu : https://www.youtube.com/watch?v=K6QiSKy2zoM (until 6:25)


To check if you have downloaded it properly, run

node -v 

 and

npm -v

and check whether the version of node and npm is being displayed or not.
**IT IS VERY HIGHLY RECOMMENDED THAT YOU USE A LINUX DEVELOPMENT ENVIRONMENT.

This article assumes a fair understanding of Javascript, so if you're a complete beginner with Javascript, we'd suggest you brush up on your basics with Javascript before moving ahead.

Coming to the asynchronous nature in Javascript, consider the following code : 

setTimeout(() => {
    console.log("2 seconds have past");
},2000);
setTimeout(() => {
    console.log("? seconds have past");
},3000);

setTimeout is a function which takes in a function and number of milliseconds as parameters, and executes the function after the specified number of milliseconds. Therefore, if the program had run synchronously, it should've taken 5 seconds for the program to terminate. But owing to the asynchronous event driven model of Node.js, it only takes 3 seconds to do so. Both the requests are serviced simultaneously(pushed into the event queue), and the functions are executed as and when their timers are elapsed.

Considering a similar example in real servers, there is always a delay between the server requesting the database for some entities and receiving them. And there would be many other independent operations you would want to perform apart from this query to the database. So would it be ideal for us to wait until the database returns a response before we can start executing other independent operations? Certainly not, and hence Node.js has shown amazing response and service rates and has succeeded in grabbing the attention of the server side development world.

Create a file "add.js" and paste the following code in it : 

const add = (a,b) => a+b;
console.log(add(5,6));

You can execute javascript files using the "node" command.
Now open a terminal, navigate to the folder where this file is located and run ```node add.js```.
You should see 11 being displayed on your terminal.

Now create another file "index.js" and paste the following code in it : 

const add = require('./add');
console.log(add(5,6));

and change the code in add.js to : 

const add = (a,b) => a+b;
module.exports = add;

Now run "node index.js" in your terminal and you should see 11 being displayed. What you just did is convert your file into a "node module". You might have several tens of thousands of lines of code in your project, so it would be practically impossible(and also really really dirty) to write all of that code in a single file and expect another developer to understand it fully or find bugs. Therefore, you divide your code into a certain set of modules where each module contains logic pertaining to a certain feature, because dealing with a few hundred lines of code at a single time is way better than several tens of thousands of them.

You have a function add, and you want to use it in some other file, so you have to "export" that file. To do so, you would write "module.exports = add". For using this function which we have just "exported" in another file, we will have to "import" it in that file. There are several ways of importing files, one of which is using the require statement. You can import a module by mentioning the path of the module you want to import(yes, the .js extension is not necessary while importing files) and that module will now be available to you in the second file.


This would be the right time to introduce you to npm, or Node Package Manager. npm is what manages the ecosystem of node modules(or packages). You might have to install several external libraries(modules) for your projects or associate certain keywords to run some scripts, and the Node Package Manager does it all for you.

In the same folder that you have your add.js and index.js files, run the command

npm init

and for now, you may accept the default entries for the fields asked by pressing enter.

This command initializes a new node project which in-turn can be used as a package by another project. You may now find a file named "package.json". This file, as quoted by my friend Mallikarjun, is a "blueprint" of your project. It contains the name, version, description, main(entry point), scripts, author, and as you shall see further, the dependencies of your project, i.e., a list of external libraries/modules that you're using in your project.

Next, run the command

npm install express

This is how you install an external dependency(library, module or a framework), in this case, express. You might see that a new folder named "node_modules" has been created with a large list of directories in it. All your installed dependencies, and the dependencies that your installed dependency depends on will be stored in this directory. Express is a flexible and minimalistic web framework for Node.js. Basically, it makes our job easier by providing us with a robust set of features, one of which we would extensively use, routing. At this point, I'd suggest you read the article, "Software Development: A Lost Art" by Shubham Shukla sir, you can find this article at page 20 in Abhishar v9.0(http://aasf.in/abhishar/Abhishar%20Volume-9.pdf). A few technical terms of utmost importance have been beautifully explained in this article.

Now open your index.js file and replace the existing code with the following code : 

const express = require("express");
const app = express();

const PORT = 5000;
app.listen(PORT, console.log(`Server started on port ${PORT}`));

Whenever we require a module using just the name of the module and not the path( as in the case of require("./add") ), node will look for the package in the set of default packages provided by it(analogous to math.h or string.h, which are in-built modules which can be included in your C or C++ code) and in the "node_modules" folder. If that module is not present in either of them, node will throw a "cannot find module" error. Therefore, in case you encounter this error, make sure you have installed the package properly before requiring it, or if you have required a module which you have written, make sure you have specified the path of the module correctly.

Here, we have required the "express" package, and node found it in the node_modules folder since we have installed it earlier. The "const app = express()" statement creates a new express application for you and assigns it to app. The intricacies and complexities involved in this, as to how express actually works under the hood is out of the scope of this article( The whole point of using express is to avoid those intricacies and complexities and let express handle it for us ), and if you want to know more about the working of express(I'm not sure why you would want to, but just in case you do), you may refer to this article:- https://www.sohamkamani.com/blog/2018/05/30/understanding-how-expressjs-works/

The last line is of paramount importance to us. That line is actually instantiating(creating) a server on your local machine, and will now cater to all the requests on port 5000 of your local machine. You could think of your machine to be a building and that port as a flat number. So everytime there is a request on that port, i.e., everytime a doorbell is rung on that flat, app listens to it. app.listen() function takes 2 parameters, first being the port number on which it has to start the server on, and the second is a function which it has to execute once the server instance has been created.

(`Server started on port ${PORT}` : When you want to include variables in strings, you use backticks, i.e., `` to enclose the string and using variables by enclosing the variable name within ${})

Now, run

node index.js

and you will see that "Server started on port 5000" has been logged. Open a browser and type in "http://localhost:5000" and you must see a screen which says, "Cannot GET /". If that is the case, you have successfully started your server and your app is ready to service requests.

Localhost is just the default name given to your machine, which has the default IP address, 127.0.0.1, therefore, you can access the same at "http://127.0.0.1:5000" as well. The :5000 here is the port number that we talked about.

 

Summarizing everything that was discussed in this article, we first discussed what Node.js is, why it is very popular and what are the features it offers, then moved on to running javascript code using node and creating "node modules". Then we discussed what npm is and how "npm init" initialises your project, how to install external dependencies for your projects and use them. Then we installed express and used it to start a server on our local machine which is potentially capable of handling requests.

What these requests are, how to "route" them, how to handle them and how to send a "response" to these "requests", we will see in the upcoming articles.

 

This article is the first in a 3-article series, which covers the "what", "why", "how" and the basics of node.js. 

In the next article, we will learn how to service requests that our app receives and send responses corresponding to those requests. Stay tuned!

 

This series of articles could not have been possible without the invaluable efforts of the co-organizers of Web Week 2020, Mallikarjun Katakam(https://www.linkedin.com/in/katakam-mallikarjun-668096183/) and Shweta Chaurasia(https://www.linkedin.com/in/shweta-chaurasia-419376187/).

 

In case of any queries, you can find me at https://www.linkedin.com/in/guna-shekar-proddaturi/.