Getting started with Node.js, Installation and basic scripts

Pankaj Panigrahi
5 min readJan 9, 2019

--

This article is the 2nd of the article series which will help you grasp different concepts behind Node.js and will empower you to create production ready applications.

While writing for this series of articles, I have assumed that the reader has some basic experience of working in Node.js and has some foundation of javascript.

If you don’t have basic knowledge on JS and Node.js. I would suggest to go through the following links.

https://nodeschool.io/#workshoppers

Check out the following tutorials of the above link:

javascripting, functional-javascript-workshop, learnyounode, expressworks, learnyoumongo

I will show some basic things with Node.js in this article too. So, Don’t worry :)

First download Node.js LTS from here: https://nodejs.org/en/download/

Please note that npm gets installed automatically when you install node.js.

For starting a node project we use npm init.

Enter the details as shown in the image and confirm with yes. This is similar to git init where you initiate a repo.

This creates a file package.json. This is the most important file of your project. Not only it will list out all the details of your project, but it will also keep track of all the dependencies of you project.

You can also put custom commands in this file.

{
"name": "02_basic",
"version": "1.0.0",
"description": "This project is made for medium article",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"node.js","basics"
],
"author": "Pankaj Panigrahi",
"license": "ISC"
}

Let us write our first node.js program.

Create a .js file and write the following line

console.log("Hello World!");

and run the file name by following command

node <file-name.js>

Your Hello world program in node.js is done. Now let us move to reading a file.

Let us first create text file in the same project as below:

Create a new js file or edit the old file. First let us import the fs module of node.js. This is an inbuilt module given by node.js which helps us read the contents of the file. Import using the command below.

const fs = require(‘fs’);

Then paste the following code below:

console.log(' Start *********************** ');
fs.readFile('file1.txt', 'utf8',(err,data)=>{
if(err){
throw err;
}
console.log(data);
})
console.log('End ***********************');

fs module provides us with the function readFile which takes 3 arguments : 1st one is the file path, 2nd one is text-format and the third one is the callback function which should be called once the file is read.

Now, guess the output. If you think the output will be as below:

Start ***********************
.... Ba Ba Black Sheep Poem ....
End ***********************

Then you are wrong. The actual output will be as below:

If you go back to the previous article, we have understood how callbacks and event loop works. This is another example of it. The file reading operation (I/O operation) happens asynchronously. The Thread doesn’t stop at this line fs.readFile(..). It continues the execution and once the file is read it invokes the callback function passed.

This is how Node.js gives us a leverage while performing I/O operations. But in some cases you would want to do the file reading synchronously. fs provides a function for that too. readFileSync functions does that exact thing.

console.log(' Start *********************** ');
let poem = fs.readFileSync('file1.txt','utf8');
console.log(poem);
console.log('End ***********************');

The output is as expected. Normally, Node.js provides both async and sync methods for maximum operations.

Now for the third example, we will be creating a basic webserver using another inbuilt module http . Please note that in later articles we will be using express on top of node.js to create web servers.

Import using the command below.

const http = require('http');

And then paste the following code below:

const server = http.createServer((req,res)=>{
res.write('Hello World !!');
res.end();
})
server.listen(30008,()=>{
console.log('Server Listening on 30008')
})

http module provides a function createServer to create a web server object. It takes a requestListener function as an argument. This function has two parameters:

  1. Incoming Message Object (commonly referred as Request Object)
  2. Server Response Object (commonly referred as Response Object)

These two parameters are the most common objects while working with APIs. Request Object will have request headers , body , params etc. Response Object has methods for handling the response stream back to the user. And we will very often set the status and data of Response Object.

We write data to the response stream using res.write and then end the stream.

The server.listen() method creates a listener on the specified port or path

Run the code as shown in the image.

Open your browser, go to “localhost:30008”

You should see the following output.

The code base for the current article can be found in the link below:

https://github.com/pankaj805/medium-02_basic

In the next article, we will see how to install external dependencies specially babel.js and configuring babel for our project.

Done for the day !

If you liked the article, you can 👏 the story and share it with others. You can find the entire article series here.

--

--