Node.js

Node.js Introduction


Node.js is a JavaScript runtime that allows developers to run JavaScript on the server-side. This means that instead of just using JavaScript to create interactive front-end experiences, you can also use it to build back-end systems, such as APIs and web servers.

To get started with Node.js, you first need to install it on your computer. This can be done by downloading the installer from the Node.js website and running it. Once installed, you can access the Node.js command line interface (CLI) by opening up a terminal and typing "node".

One of the most common uses for Node.js is creating a web server. This can be done using the built-in "http" module. Here's an example of a simple web server that listens for incoming requests and sends back a "Hello, World!" message:

 


In this example, we first import the "http" module using the "require" function. Then, we create a new server using the "createServer" function. This function takes a callback that gets called every time a request is made to the server. In the callback, we use the "end" function to send back the "Hello, World!" message. Finally, we tell the server to listen on port 3000 using the "listen" function.

Another common use for Node.js is creating APIs. This can be done using a framework such as Express. Here's an example of a simple API that returns a list of users:

 

In this example, we first import the "express" module and create a new app using the "express" function. Then, we define an array of users. We use the "get" function to create an endpoint that returns the list of users when a GET request is made to "/users". Finally, we tell the app to listen on port 3000 using the "listen" function.

These are just a few examples of what you can do with Node.js. With its powerful and versatile runtime, you can create a wide variety of back-end systems and applications.