First time with Node.js
Tags: node, javascript, beginners
Published: 2021-05-18 16:38:57

## What is node?

When we are developing a website we normally talk about code inside the frontend (browser) or the backend (server). In the past, Javascript was confined to work only in the browser (frontend) which was used to add interactivity to the website. We never used to run Javascript directly on the computer or server but in recent times Node.js has made that possible. Node.js allows us to run javascript on the server side (backend) or directly on computers.

Computers can’t directly understand Javascript or compile them down directly into machine code. However, in browsers there’s an engine called V8 engine written in C++ which compiles Javascript into machine code at runtime allowing the computer to understand Javascript within the context of the browser (browser confined).

Outside browsers, the V8 engine is also present in Node.js written in C++ hence it can also take our Javascript, run it through the V8 compiler running inside of it and compiles it into machine code making it possible to run Javascript on a computer or server and not just a browser.

However, Node is more than just a compiler. It can be used for the following;

1.Read and write files on a computer
2.Connect to a database
3.Act as a server for contents

In brief terms, the role of node in a website is basically to run Javascript in the backend and then handling requests coming in from a browser.

## THE GLOBAL OBJECT
The global object is the window object equivalent of node. In node we can get access to the global object with several different methods and properties attached to it just like as do in a browser with the window object. To see these methods and properties we can run;

console.log(global);

and then we get to see those properties.

## MODULES IN NODE.JS

Node comes with several different core modules that come with different methods and property. An example is the “os” module which stands for operating system. It gives us every information about the operating system node is running on. To import a module we use the require method hence;

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dj8zvsrvpntf2wc4cck6.png)

There are several different modules in node and I will explain the use of some of them.

## FILE SYSTEM CORE MODULE
The file system core module in node allows us to perform functions such as creating files, reading files, deleting files and many more.

The in-built module used in interacting with the file system is the fs module. We import it by using;

fs.readFile

It takes two arguments, the first argument is the relative path to the file we want to read and the second argument is a function that fires when the reading of file is complete. Inside the callback function we take two things, (err,data). The error “err”, if there was one and the data which is the stuff that we read

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m3c9k9pia28rph6nnvwp.png)

### writing files

fs.writeFile

It takes three arguments, the first argument is the relative path to the file we want to write to, the second argument is the text we actually want to write to the file which replaces any existing file then finally a callback function.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ywsm8yyzuov4e3zmnoyw.png)

### creating or making a directory

fs.mkdir

Make directory takes two argument. We just need to specify where we want to create the directory and what name to give to it and then we fire a callback function when it is done. The callback function takes an err which informs us when an error has occurred.
However, if we run the make directory code more than once with the same file name we get an error message. In other to ensure that the code only runs if the filename does not exist we use the existSync method

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eatxiis79ucrzhao5u4v.png)

### deleting or removing a directory

fs.rdmir

it takes two arguments, relative path to the folder we want to delete and then a callback with an error message.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r9hglme9vl1bmbkibovx.png)

### deleting a file

fs.unlink

It takes two arguments, the relative path to the file we want to delete and then a callback function

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nve3z2ram6r4u8dz6olu.png)

We have seen how node can read, create and delete files from a computer now but sometimes those files can be very very very large that it would take a long time for those activities to happen, In other to combat that we use something known as streams. With streams, we can start using a data before it is fully read.

## STREAM

### reading streams

fs.createReadStream 

We create a variable that takes createReadStream which takes an argument of where we want to pass data from through this stream.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k3p6kv6b0rb7qwa9j5mp.png)

the variable we have created now takes in two arguments, the data and then chunk, the chunk represents a chunk of data. The “on” on our readStream I similar to an event listener but this time we are listening to a data event, anytime we get a chunk of data we fire the callback function and we get access to the new stream of data.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uynuhubt4mejizf2j39w.png)

### writing a stream

fs.createWriteStream

We create a variable that takes fs.createWriteStream and then where we want to write the stream to as an argument. And now, anytime we get a new stream we have to write the chunk to the file we want to write to 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l6fc64wf2wqeru1vkg9b.png)

### piping

This is a more direct way of sending readable data directly into the writeStream and we use the method “pipe”

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k6t72ru8620w9k22l9r2.png)


## CLIENTS AND SERVERS

When a user goes to the browser and types the name of a website, a request is sent to the server which also responds with the html, css and javascript used in creating that web page. There are more than a million servers out there, how does the request know which exact server to request from?

That is possible due to IP addresses and Domains.

### IP Address and Domain Names

IP addresses are like addresses for computers which are connected to the internet and all computers connected to the internet have unique addresses that help in identifying them. There are some special computers known as hosts meaning they host websites on the internet. If you create and publish a website it will be hosted on a computer somewhere and that computer will have an IP address that would be used to identify it. Now, if we want to connect to that computer acting as the host server we need to know the IP address to be able to do it. We can now type that IP Address in the address bar if we wanted to connect to our server. Now, IP addresses are just a series of numbers and they would be really hard to remember hence we use domain names to mask these IP addresses and when we type these domain names into a browser it will find the IP address associated with it and then it would use that to find the computer hosting the website and it will use that to communicate with that computer. This type of request is known as the GET request. Which occurs anytime we type a domain name in the address bar or we click on a link. This type of communication is via HTTP and it stands for Hyper-Text Transfer Protocol. HTTP simply is a set of instructions that dictates how communication between the browser and the server occurs.

## Creating a server

In node we actually write code to create a server and listen in on requests coming to the server.

#### STEP 1

We have to require the http module and store it in a constant of your naming. Here we used http
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2so8ts99qe6k3qj7y9iw.png)

#### STEP 2

createServer()
we called the createServer method on the http constant.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7r84b9ua77pmzedirfiq.png)

The createServer method takes two arguments, the request object “req” which represents requests made by any user and then the response object “res” which represents the response of the server to whatever request.

![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/55y5kp9uor04crcaelbx.png)

As it stands, we have a server with no ability to listen to any request. In other to achieve that we have to create a listener event which takes three arguments. The port number and in this case we are using port number 3000 and then the host name and this time we are using local host and finally a callback function that fires when we start listening in for request

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3r6fxsuesutp9lnrr2xv.png)

## Localhost

A local host is like a domain name on the web however it has a specific IP address called the loopback IP address and that address is 127.0.0.1 and it takes us back to our own computer. That means, when we connect to the localhost domain in our browser, the browser is actually connecting back to our own computer which is then acting as a host for our website. So the host name localhost means to listen for request coming to our own computer.

## Port number
The port number represents a specific port on our computer that a server should communicate through. For instance, when you have various communication softwares on your computer like whatsapp, skype and telegram they would all have specific port numbers that their various servers would communicate through on our computer so not to mix up information

In the long run of things, when you type localhost followed by a port number (localhost:300) the browser will know how to communicate with our computer via the particular port number which is where our server is going to be listening

## Requests and Response

### Requests

The request object contains information about the request that the user sends. When you log out the request object you see various methods available such as the url, the method used and so on.


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lxfz938fx1wruwns4ttc.png)

## Response 

The response object is what we use to send a response to the browser. We have to formulate some kind of response anytime a request is made or the browser is left hanging. The first step in doing this is to formulate the response headers, the response headers gives the browser some information about what kind of response is coming back to it for example a GET or POST response, what type of data we are sending back.

### Setting content type headers

We do that by first using the setHeader method on the res object. There are a lot of different types of headers but in this case we are using the content-type and this could be in either text, html, json or anything but in this instance we are using text/plain.

**Now, how do we actually send that data to the browser?**

We use the res object and the write method to write to the response as an argument and when we are done we have to end the response using res.end()

This occurred in three steps;
1.	We set the header for the content type
2.	We write whatever content we want to send to the browser
3.	We end the response we send to the browser.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4r62nx8x77hlfsxt4kx8.png)

### returning html pages

#### Step 1

We must require the file system as fs

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lycj32pyq7dwd8mc4wjo.png)

#### Step 2

We must read the files like we always do 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wsdf8o241ouz3fs55bdx.png)

#### Step 3

We must write the files with res.write

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qzv3kwlp7hzl7thktk0c.png)

### Basic routing

Currently we are returning a single html regardless of the url the user requests for which is wrong, we have to find a way to send specific page url depending on what the user requests for. For instance, if the user requests for the about page we have to find a way of identifying the request and sending the corresponding url.

#### How do we do this?

1.	We set up a path variable, the path variable is basically the path to the folder containing all the html pages
2.	Then we look at the users request url using the switch. That is, did the user visit eg “/” or “about” or many more
3.	Then we create various cases, so if the request url matches any of the cases then we add the path created to the html file and then break out. If the request doesn’t match any of the cases we then send a default 404 page


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aylwx79y585s3lik1fy7.png)

### Status codes
The status codes describes the type of response being sent to the browser and how successful the response was;
200 – This means everything was okay with the response
301- Signifies a permanent redirect
404 – means the file is not found
500 – means some kind of internal server error

#### There are so many codes but its best to learn the ranges

100 range – information for the browser
200 range – success codes whereby everything goes to plan
300 range – codes for redirect
400 range – user or client errors
500 range – server error 

We can add the statusCode method on the response object so we can get information anytime things go as planned or not

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5yp77axar4cchke9dwv6.png)

### NPM (Node Package Manager)

So far we have seen how to use core modules and pacakges that are built into the node core for example the fs module to work with the file system but what if we want to use some additional packages for extra features in node that are not available in the node core? There are about 1000s of user-made packages that we can use with node and we can install them using npm. It is a tool that we can use to install, update or remove packages onto our computer directly and also into our individual projects. Most of these packages are available at www.npmjs.com.
One of the first packages we are going to install is nodemon for our development server so we don’t have to keep restarting it manually.


# TO BE CONTINUED ....