Node.js
Node.js is an open-source, server-side runtime environment that allows developers to run JavaScript code outside of a web browser.
What is NPM?
NPM stands for "Node Package Manager." It is a package manager for Node.js.NPM is the default package manager for Node.js and is used to manage and distribute packages (libraries, frameworks, and other code modules) written in JavaScript.
Initialize Node.js project
The npm init
command is used to initialize a new Node.js project and create a package.json
file. The package.json
file is a crucial component of Node.js projects as it contains metadata about the project and its dependencies, making it easier to manage and share the project with other
Writing our first program
Create a file named 'index.js', for simplicity we are writing a basic program where we are printing "Hello World".
console.log("Hello world")
console.log will print whatever is written inside it on the console. As we are using NodeJS we don't need any browser to run this code, we can run this code using -
node .\index.js
Now, after every change in 'index.js' file, we again have to run node. While creating a big project we can't keep running node again and again as it is a very exhaustive task to do. Here comes nodemon to help us out.
What is nodemon?
nodemon
is a utility tool used in Node.js development to monitor changes in your Node.js applications and automatically restart the server when changes are detected. Hence saving developers time and effort.
Installing nodemon
npm install -g nodemon
-g is a global flag that installs nodemon globally.
Running nodemon
nodemon .\index.js
Creating a Server
Servers are essential components of website development, as they handle critical functions such as request handling, data management, security, and performance optimization. They are responsible for processing user requests and providing the necessary resources to create a seamless and interactive user experience on the web.
const http = require("http");
const server = http.createServer((req,res) => {
if(req.url === '/')
{
res.end("<h1>Home Page</h1>")
}
else if(req.url === '/about'){
res.end("<h1>About Page</h1>")
}
else{
res.end("<h1>Page not found</h1>")
}
});
server.listen(5000, () => {
console.log("Server is running on port 5000")
})
If we request a page whose URL is not provided in the code the server will respond with Page not found as we can see in the else condition of the code.
Here we requested a URL - localhost:5000/contact
which is not provided in the code hence the else condition will run.
Modules
To shift from common js to module we have to set 'type' in package.json
to module.
"type": "module",
In JavaScript, a module is a self-contained unit of code that encapsulates specific functionality. Modules are a way to organize and structure your code into reusable and maintainable components.
Now if suppose, if we create another file called "feature.js" we can write a function inside this file and export it to the "index.js" file.
feature.js
export const randomGenerator = () =>{
return `${Math.random() * 100}`;
};
index.js
Now we have to import the function in index.js file. We can do so by -
import { randomGenerator } from "./features.js";
Complete index.js file -
import http from 'http'
import { randomGenerator } from "./features.js";
console.log(randomGenerator())
const server = http.createServer((req,res) => {
if(req.url === '/')
{
res.end("<h1>Home Page</h1>")
}
else if(req.url === '/about'){
res.end(`<h1>Random number is ${randomGenerator()}</h1>`)
}
else{
res.end("<h1>Page not found</h1>")
}
});
server.listen(5000, () => {
console.log("Server is running on port 5000")
})
Now, If we navigate to '/about' section we will get a random number.
Synchronous vs Asynchronous programming
So, before moving further let's understand the difference between Synchronous and Asynchronous programming with the help of an example -
Synchronous
Code-
var a =1;
var b =2;
console.log(a);
console.log(b);
Output-
In this example every line will run serially, i.e., the first line will execute first and the last line will execute at the last. As a result, the output will be logged in serial order, i.e., 1 and then 2.
Asynchronous
Code-
var a =1;
fetch("/", function () {
console.log("Loaded");
});
console.log(a)
In this case, the output will be -
1
Loaded
This happens because the fetch function takes time and the rest of the code does not wait for it to be over, this a prime example of an Asynchronous function as every line is not getting executed serially.
HTTP Methods
The four most commonly used HTTP methods are -
GET: The GET method is used to retrieve data from a specified resource. When a client sends a GET request to a server, it asks the server to return some data, such as a web page, a file, or information from a database. GET requests are typically idempotent, meaning making the same GET request multiple times should have the same effect as making it once. They should not have any side effects on the server.
POST: The POST method is used to send data to the server to create a new resource. When a client sends a POST request, it typically includes data in the request body, which the server can use to create a new record or resource. POST requests are not idempotent because each request may result in a new resource being created.
PUT: The PUT method is used to update an existing resource on the server. When a client sends a PUT request, it typically includes data in the request body that represents the updated resource. PUT requests are idempotent, meaning that making the same request multiple times should have the same effect as making it once.
DELETE: The DELETE method is used to request the removal of a resource from the server. When a client sends a DELETE request, it asks the server to delete the resource identified by the URL. DELETE requests are idempotent because making the same request multiple times should have the same effect as making it once.
import http from 'http'
import { randomGenerator } from "./features.js";
console.log(randomGenerator())
const server = http.createServer((req,res) => {
console.log(req.method)
if(req.url === '/')
{
res.end("<h1>Home Page</h1>")
}
else if(req.url === '/about'){
res.end(`<h1>Random number is ${randomGenerator()}</h1>`)
}
else{
res.end("<h1>Page not found</h1>")
}
});
server.listen(3000, () => {
console.log("Server is running on port 3000")
})
By using console.log(req.method) we can check which HTTP request the function is generating.
As in this case GET request has been generated.
The next blog will be about express so be tuned.
Thanks!