What is node?
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
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;
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;
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;
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
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.
creating or making a directory
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
deleting or removing a directory
it takes two arguments, relative path to the folder we want to delete and then a callback with an error message.
deleting a file
It takes two arguments, the relative path to the file we want to delete and then a callback function
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.
We create a variable that takes createReadStream which takes an argument of where we want to pass data from through this stream.
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.
writing a stream
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
This is a more direct way of sending readable data directly into the writeStream and we use the method “pipe”
CLIENTS AND SERVERS
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.
We have to require the http module and store it in a constant of your naming. Here we used http
we called the createServer method on the http constant.
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.
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
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.
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
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.
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;
- We set the header for the content type
- We write whatever content we want to send to the browser
- We end the response we send to the browser.
returning html pages
We must require the file system as fs
We must read the files like we always do
We must write the files with res.write
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?
- We set up a path variable, the path variable is basically the path to the folder containing all the html pages
- Then we look at the users request url using the switch. That is, did the user visit eg “/” or “about” or many more
- 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
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
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.
Top comments (0)