Getting Started with Node.js
Node.js is server side async runtime.
Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. — Nodejs.org
Step 1: Install Node.js
Visit Nodejs.org and download and install Node.js for your machine. (This tutorial using Linux based machine)
- After installation is finished open Terminal and write following command:
node -v
- This should output node version if Node.js is installed correctly:
v8.6.0
Step 2: Write your first ever Node.js code
- Create your first Node.js file using following command in terminal:
touch HelloUniverse.js
- Here HelloUniverse is file name, .js is extension of JavaScript file.
- Now open HelloUniverse.js file in any of text editor tool.
Help Note: This tutorial is using VisualStudioCode, but there are many text editor tools available,
- Write following code in HelloUniverse.js
var http = require('http'); //Line 1http.createServer(function (request, response) { //Line 2 response.write("Hello Universe!"); //Line 3 response.end(); //Line 4}).listen(8080); //Line 5
Let’s execute the code. Explanation of above code is given below.
Step 3: Run the above node code.
In terminal write following command:
node HelloUniverse.js
Open following link in your browser:
http://localhost:8080
Happy Happy 😃, the node server is running in your local machine.
You are done with your first Hello Universe code of Node.js.
HelloUniverse.js explanation:
Line 1:
var http = require('http'); //Line 1
- Using require(‘http’) method, Node.js includes http module to the app. Now app is able to access HTTP module.
Line 2:
http.createServer(function (request, response) { //Line 2
createServer() method creates HTTP server.
Line 3:
response.write("Hello Universe!"); //Line 3
Writes response to the client.
Line 4:
response.end(); //Line 4
Ends the response.
Line 5:
}).listen(8080); //Line 5
The server object is listened to port 8080.
📣 Share it if you liked it, and it helped you. 📣