Node.js: JS Runtime Environment

Node.js provides a JavaScript Environment which allows the user to run their code on the server (outside the browser). Node pack manager i.e. npm allows the user to choose from thousands of free packages (node modules) to download.

Why use Node.JS?

  • Open source JavaScript Runtime Environemnt
  • Single threading – Follows a single threaded model.
  • Data Streaming
  • Fast – Built on Google Chrome’s JavaScript Engine, Node.js has a fast code execution.
  • Highly Scalable
  • Initialize a Node.js application by typing runing the below command in the command window. Accept the standard settings.
npm init
  • Create a file named index.js.

Example:
A basic Node.js example to compute the perimeter & area of a rectangle.

var rectangle = { 
    perimeter: (x, y) => (2*(x+y)), 
    area: (x, y) => (x*y) 
}; 
  
function Rectangle(l, b) { 
    console.log("A rectangle with l = " + l + " and b = " + b); 
  
    if (l <= 0 || b <= 0) { 
        console.log("Error! Rectangle's length & breadth should be greater than 0:  l = "
               + l + ",  and b = " + b); 
    } 
    else { 
        console.log("Area of the rectangle: " + rectangle.area(l, b)); 
        console.log("Perimeter of the rectangle: " + rectangle.perimeter(l, b)); 
    } 
} 
  
Rectangle(1, 8); 
Rectangle(3, 12); 
Rectangle(-6, 3); 

 

  • Run the node application by running the below command in the command window.
npm start
Arun Goel

Arun Goel

Software Developer at Atlassian

I am a programmer and I like problem solving and building products.

6

A star would make my day!

All Labs

Previous

🏆 Completed!

More Labs
Discussion

Be the first one to comment!