Understand nodejs Basics - webserver tutorial
Understanding Nodejs
Nodejs is an open-source framework for building Server-side applications based on javascript.
It is a javascript runtime based on the Chrome V8 Javascript engine.
You can write your web server using this environment.
Nodejs is growing popular day by day because of its features, simplicity, and architecture.
Nodejs can run on any operating system like Windows, macOS, and Linux/Unix/Ubuntu. It is a platform Independent. You can also check other posts on npm command deprecate option is deprecated
Nodejs Advantages or pros
- Provides Non-Blocking and Event-Drive programming features to handle the concurrent request
- It is based on javascript
- Scalable and network applications can build with simple code
- Simple to learn
- It is a single-threaded model
- Performance is good as it uses javascript on the server-side
Disadvantages or cons
- Learning Curve
- Not suitable for Multithreaded Model
- Not enough tools
Basic Web server Example
A web server is a server in which clients send the request to the server, and in turn, the server returns a response. Here request
and response
are based on HTTP protocol.
To start the basic web server, First, you need a nodejs environment installed. Which provides node and npm commands.
There are many ways we can create/use a web server. I am discussing custom code and using another npm library.
Nodejs Http Module example
In this, Going to write code for our server using inbuilt modules.
It is easy to write a web server using an HTTP module.
const http = require("http");
const defaultPort = 3000;
const handler = (request, response) => {
console.log(request.url);
response.end("Basic Web server Server");
};
const webserver = http.createServer(handler);
webserver.listen(defaultPort, (error) => {
if (error) {
return console.log("Error occurred during starting a server", error);
}
console.log("Web server is up and running at 3000 ................");
});
You need to use the HTTP module and import using the required function
Using http-server npm package manager
the http-server library provides web server capabilities.
First, you need to install it using the below command npm install http-server -g this installs the http-server
package globally which can be accessed from anywhere. we are accessing from the command line
Syntax
http-server path options here the path defaults to a public folder, if the public is not available, / considered
Options
There are various options you can configure it
web server configurations
-p for the port which the server listens on
-s HTTPS enabling
-o Once the server is up and running, automatically opens a browser window.
This is about the basics of the nodejs environment.