Node.js is an open-source, cross-platform runtime environment that enables JavaScript for server-side application development.
Install NodeJs-
You can download and install Node.js from its official website: https://nodejs.org/
Node.js Application Create-
- create new folder for the project.
- in your folder first create example.js file (You can use diffrent name no issue).
- open your file and write javascript code & save file.
console.log("Hello, World!");
it print Hello Word! on your cansole.
Run Code-
open your terminal and go in folder using cd command & run your application using this command.
node example.js
Node Package Manager-
Use this command for package manager
npm init
Creating a Simple HTTP Server-
it contain 3 parts
Step 1. Import required modules
var http = require("http");
Step 2. Create server
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!\n');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
Step 3. Read request and return response (example.js)
First Combine Step1+Step2 and run code for request and response.
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!\n');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
Run your code using this command
node example.js
Now server is started
open it op browser
Open http://localhost:3000/
in any browser. You will see the following result.