Tute 01: Nodejs, NVM and NPM - ariffira/node-basic GitHub Wiki
Node Js:
- allow JavaScript on Server (JS runtime on Chrome)
- Non-blocking and faster
- free to use and extension ".js"
- Event-driven
- made in js+c++ code, so you can use c++ similar code with Js code ;p
NVM(Node Version Manager):
Why needed?
- allow switch between different versions of Node and define default one and keep track of node
- possible to check that your app can work with other nodejs version. you can test, fix bug this way. You can check other developers work and try to fix errors
- save time for developers
- easy to work with many clients
- commands like:
nvm install nodeVersion
nvm use nodeVersion
//the version you want to use
nvm alias default nodeVersion
// then later u can call nvm use default
nvm alias myTest nodeVersion
nvm ls
NPM(Node Package Manager):
- package manager or modules set of JS library
- easy to download and save
npm install --save packageName
- save all npm package in node_modules
Important links:
After installing nodejs we can play with it from REPL (Read Eval Print Loop) console as node
command as below:
>node
> 1+1
2
> var x =5
undefined
> x
5
> var x=9; x;
9
> x+10
19
> var today = new Date()
undefined
> today
2018-08-24T19:52:58.173Z
> for (var i=0; i<10; i++) {
... console.log('Print my number:'+i);
... }
Print my number:0
Print my number:1
Print my number:2
Print my number:3
Print my number:4
Print my number:5
Print my number:6
Print my number:7
Print my number:8
Print my number:9
undefined
> function saySomeThing(data) {
... console.log(data);
... }
undefined
> saySomeThing('Hello Arif')
Hello Arif
undefined
> saySomeThing(100)
100
undefined
Modules
Some packed code/functions of JS. You can say reusable Js library. You can include them in your code and use them. If you know react or Java then its like import/export components.
To use module : require(); //a function includes module for you
Lets create a helloModule.js file and play with build in module 'http' and then create your own module and test it:
// include a build in module
var httpModule = require('http');
var portNumber = 3000;
// create a server with httpModule
httpModule.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/html'});
response.end('Hello Node JS. How are You?');
console.log('My First Node js file running on port:' + portNumber);
}).listen(portNumber);
From above code you may have some questions on mind.
- how do I know about Http module or where to find other modules?
- createServer(), writeHead(), listen() where and how to know about them?
Answer is very simple go to nodejs Api page Nodejs API resources or search in your browser how and what you could do. Most of the time other people tried or did something that will help you. Please read others problem and always compare with yours. Do something, test it and do it much cleaner way so other can read it.
Read more: http anatomy
So, lets explain little-bit the above code. I want to create a Server so my nodejs code could run. I choose HTTP server. First I need to include it using require() and then save it by httpModule name. You can give any name you like. then use this to create server. I need a port from where I can listen.
httpModule.createServer() method turns your computer into an HTTP server
// createServer creates a server for you
const server = httpModule.createServer((request, response) => {
// header, body will be here
});
Check the myModule/index.js code now. And create more module yourself like me. Ask me if you do not understand the code
Lets check FileSytem module 'fs' from my git code. There I have create, update, delete and Rename functionalities of file.
Now create a file called server.js
which we will use later also. This file has same code we did before but it has also hostName like 'localhost' 127.0.0.1 as your host with port 5000. That means you call localhost:5000 and it will work as your **server ** in port 5000.
...
const myHost = 'localhost'; //127.0.0.1
const portNumber = 5000;
// create a server with http
const server = http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/html'});
response.end('My Server Works fine');
});
server.listen(portNumber, myHost, () => {
console.log('My Server is running on port:' + portNumber);
});
You may notice now after running the server like node server
it shows console data in console without going to the browser. Because now we defined our host also. ;)
Try to do below code snippets
Read a Html file
const http = require('http');
const fs = require('fs');
const myHost = 'localhost'; //127.0.0.1
const portNumber = 5000;
fs.readFile('htmlRead/index.html', (err, html) => {
if (err) {
throw err;
}
// create a server with http
const server = http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(html);
response.end('I am reading you Html');
});
server.listen(portNumber, myHost, () => {
console.log('My Server is running on port:' + portNumber + ' and HostName: ' + myHost);
});
});
Now create some routes for node js web app as below:
- Url module: can parse the url path and pathname after localhost:5000
- here we have home page and about you page as routes
Steps:
create a routingNode directory and in their create * index.js(our server), * fileRead.js(our module), * home.html and * aboutUs.html files.
routingNode/index.js // copy code from server.js file we created initially and add below code their
...
var url = require('url');
var fileRead = require('./fileRead');
...
// create a server with http
const server = http.createServer(function (request, response) {
......
var path = url.parse(request.url).pathname;
// routes
switch (path) {
case '/':
fileRead.fileRead('routingNode/home.html', response);
break;
case '/aboutus':
fileRead.fileRead('routingNode/aboutUs.html', response);
break;
default:
response.writeHead(404);
response.write('Route not defined');
response.end();
}
});
....
Now create a module called routingNode/fileRead.js
and add below codes:
const fs = require('fs');
function fileRead(path, response) {
fs.readFile(path, (err, file) => {
if (err) {
response.writeHead(404);
response.write('File not found!');
}
else {
response.write(file);
}
response.end();
});
}
module.exports.fileRead = fileRead;
Then create two html page as you like. ;)
Asyn or Non-blocking code vs Blocking code:
Nodejs is famous for asynchronous call which means non-blocking code that we discussed initially. Now lets look at some sample code to understand it far better. I already used non-blocking code in my previous code. Did you notice? Ok you will after read this.
The main difference in short is non-blocking code has callBack and blocking code has no callback
Lets see a synchronous blocking code which will load console slower and then told you about the callback (check my asynCode folder)
// reading a file as Synchronous call
const fileData = fs.readFile('./htmlRead/index.html');//this has no callback, so code is wait or block here to finish this
So you will see something like:
Calling an asynchronous function without callback is deprecated.
Now check the same code using callback functions that will not show you any problems and in browser loading is faster without any error.
// reading a file as Asynchronous call/ non blocking by a call back
const fileData = fs.readFile('./htmlRead/index.html', (error, data) => { //this arrow function is callback function
if (error) {
throw error;
}
response.write(data);
response.end('This is a non-blocking/asyn call....');
});
Do not use sync and async code together... it will crash your app 💣
Thats cool now you know about routes and how it can read html data and also about asynchronous code. There are more nice stuffs like file upload and email system in nodejs. We will start to work on them using expressjs. Please check my other wiki files in this repo.
Thanks