800+ Companies Hiring Full Stack Developer- Register Now

Introduction to NodeJs || Basic Concepts of NodeJS

Register Yourself to get hired soon:- Register Now

NodeJS

Nodejs is easily employed as a server-side proxy. where it can handle a large amount of connection in a non-blocking manner. On the other hand, we can say It is javascript that executes on the server.

Installing Nodejs and VS code:-

we can run NodeJS by using repl or VS Code.

Note:- Some javascript commands such as document get element by id and local storage will not run in Nodejs.

Running a program

  • Create index.js file.
  • write some Javascript code inside index.file as you want to write.
  • Click on the run button to run the code or write node index.js in the terminal.

Initializing a Node Project.

in the terminal, write npm init fill up the detail and write yes. then a package.json file will be created.

Package.json:

It records important metadata about a project which is required before publishing to NPM and also defines functional attributes of a project that npm uses to install dependencies, run JS etc.

Accenture Mass Hiring For Freshers:- Apply Now

What is NPM?

Npm Stands for Node Package manager, It puts modules in place so that nodes can find them and is used to publish install and develop Node programs. Run NPM to help to get the list of available commands. For Example:- if we want to check the npm version we can use the command:- npm –version.

Installing Package.

To install it write.

npm install express --save

You will see that “express –version” written in your package JSON after installing it. A node module folder also gets created and package.lock.json is created. package-lock.json is a large list of each dependency listed in your package.json, the specific version and location of module etc.

Note. If you want to uninstall the express package you can write in command prompt or terminal.

npm uninstall express

we completed the installation process for our node app. but when we run that app there will be a problem with that the problem is that if we update something in the code it will note update at the server directly or automatically. for that, we will have to run the app again and again. To solve this problem we have to install another package which is ‘nodemon’. Nodemon will help us to update our server as per our code without running code again and again.

let’s install node mode using the following command

npm i -g nodemon

Development Dependency: Package that is used during development. To install the package as a dev dependency.

npm install --save-dev nodemon

Angular CLI package:- To install angular CLI package write in terminal or Command Prompt.

npm i @angular/cli

Import and export. Create two files index.js and second.js. firstly we will export code from second.js and then import it into index.js. let’s write the following code in the second.js file.

harry={ name:'piko',favnum:36, developer:True}
module.export= Harry; // name of object

write code in index.js

Const Lovish=require("./second")
console.log('helloworld", Lovish)       
//both object will get printed        

Module Wrapper Function:- let’s understand the basics of wrapper classes. It wraps the entire code inside a function before execution. This function is termed a module wrapper function.

(funtion(exports,require,module, _filename,_dirname){
console.log(export.require,module, _filename,_dirname)});

As a result value of each variable gets printed.

OS: It is a built-in module. create a file index2.js to import it. And write const os=require(‘os); for example, if we want to know about the available free memory we can write the following code.

console.log(OS.freemem())

//There are many function, chack out by yourself.
os.platform()
os.homedir()
os.hostname()
os.release()
and much more

Asynchronous non blocking Input output model

NodeJS process must wait until a non= javascript operation completes. But this does not happen in NodeJS until it is doen intentionally.

Example:-

fs.readfile('file.txt','utf8',(err,data){
console.log(err.data)})
console.log('finished reading file)

Output: Finished reading file null this is a file. The second statement gets printed first as first one is time consuming and nodeJS allowed the second to run.

Stop NON-Blocking use by following command:-

fs.opensync(path[,flags,mode])
fs.rename(oldpath, newpath,callbacks)
fs.ublinkingsync(path)

Tempcode runner.js

Automatically gets created. when a portion of code is run.

Common JS module (import/export). Create two files named module first.js and module second.js. write following code In module second.js

function name(){
console.log("sample is complax")}
module.exports=name;

write the following code In module first.js

const name=require("./module2")
name()

on being run it prints simply is complex.

ES6 module:- to understand the concept of the ES6 module we are going to create two files. the module second.mjs and module first.js. As you can see in the first file extensions we used mjs which is used for the ES6 module. In the ECMA script module, require and module.export can’t be used.

In package.json add “type”:”module” to use ES6.

In second.mjs

export function name(){
console.log("hello world")}

in first.js

import {name} from "./module second.mjs"
name()

” Hello, world” will be printed on the terminal. in this way. you can import-export function among the files

We can import/export more than one function. In second.mjs

export function name(){
console.log("hello world")}
export function name2(){
console.log("hello world2")}

in first.js

import {name, name2} from "./module second.mjs"
name()
name2()

Default Function:-

It allows the formal parameters to be initialized with default values if no value or undefined is passed

for example:-

export default function name(){
console.log("helloworld")

Now. if you try to import any function which does not define then the above value “hello world” get imported. we can use the ‘*’ operator to import/export all the values.

import * as a2 from "./module second.mjs"
console.log(a2)

URL module:- if we want to import URL we will write like import URL from ‘URL; we can get many functions of URL from the documentation which you can use to set a portion of the URL

For Example:-

URL.hostname:- Gets and sets the hostname of the URL.

URL.host:- It gets and sets the host portion of the URL.

The difference between the two is that URL hostname does not include the port.

URL.password:- Gets and sets the password.

URL.hash:- Gets and Sets fragment portion of the URL.

There is many more checkout by yourself. for example:-

const myurl=newurl('https://ex.arg')
const myurl.pathname='/a/b/c';
const myurl.search='?d=e';
const myurl.hash=#fgh
console.log(myURL)
//prints all value of URL indivisually
console.log(myURL.href)
//print your URL

Events Modules:-

Every action on a computer is an event. NodeJS has a built in module called ‘event’ , where we can create fire and listen for our own events. for example:-

const eventEmitter = require('events');
class myEmitter= extends EventEmitters {};
const myemitter=new MyEmitter();
//when this event is fire the below code will run.
myEmitter.on(waterfall',()=>{
console.log('turn off motor!');
settimeout(()=>{
console.log('please turn off the motor');
}, 3000);});
myEmitter.emit('waterfall');
//here the event is fired.

The output of the above code is :- In the terminal we will get ‘turn off motor’ printed and after every three second ‘please turn off the motor’ will be printed.

Note:- It is very helpfull when you are building a realtime application.

Now we are going to building an http server.

import const http.require('http');
const port =process.env.PORT//3000;

We can set the environment variable port to tell our webserver what port to listen on. If no port is there, listen on 3000. if you want to open the server then write ‘localhost:3000’ in the search bar of the browser

http.createserver():- this method turns your computer into an HTTP server

Syntax

http.createserver((request,response)=>{ reponse.end();})

Status code:- It includes whether a specific HTTP request has been successfully completed.

const port=process.env.PORT//3000;
const server=http create server((req,res)=>{ res.statuscode=200;
res.setheader('content-Type':'Text/HTML') 
//it means request is served as HTML not plain Text
res.end('<h1> This is code </h1>);});
server.listen(port,()=>{console.log('server is listening on port ${port}');});

This will create a server, To access it write ‘localhost:3000’ in the searchbar of your browser

Leave a Comment