Node. js Basics: Server-side JavaScript

Node. js is a powerful runtime environment that enables the developers to write JavaScript code on the server side. Unlike the normal JavaScript which is usually run on the browser, Node. js allows JavaScript to be used for the development of server-side applications hence one can be able to develop applications that have both front end and back end interfaces.

What is Node. js?

Node. js is based on the V8 JavaScript engine that is the same engine that Google uses for Chrome. It was created by Ryan Dahl in 2009 and it enables JavaScript to be used in non-browser environment and enables the creation of standalone applications with efficient server side programming.

Key features of Node. js include:

1. Non-blocking, Asynchronous I/O: Node. js employs an event-driven, non-blocking I/O model which is quite effective as compared to other programming languages and is suitable for applications that have real-time needs.

2. Single-threaded with Event Loop: First of all. js uses a single-threaded event loop which enables it to manage multiple requests where it doesn’t have to create other threads hence improving efficiency.

3. NPM (Node Package Manager): It is a point in the network, where the data is processed and or retransmitted. javascript has a default package manager, NPM, which is the largest software registry in the world. It helps the developers to easily install, share and manage dependencies in any project they are working on.

4. Cross-platform: Node. js is a cross-platform which means that it can be used on different operating systems such as Windows, MacOS and Linux.

Installing Node. js

To start using Node. If you are using javascript, you’ll need to download it on your computer. Node. js can be downloaded from the [official website](https:In order to download Node.js visit the official website of Node.js (http://nodejs.org/), there you will find the suitable installer for your OS.

Once installed, you can verify the installation by running the following commands in your terminal or command prompt:Once installed, you can verify the installation by running the following commands in your terminal or command prompt:

node -v

This command will help to know the version of Node.js installed in the current system. js.

npm -v

This command will show the version of NPM that is installed in your system.

Creating a Simple Node. js Application

Node. most js applications are executed from the command line. Now let us write a very basic “Hello World” web server using Node. js.

1. Create a new directory for your project:Create a new directory for your project:

mkdir my-node-app
cd my-node-app

2. Initialize a new Node. js project:

npm init -y

This command will generate a ‘package. json file, which contains information about the project and its dependencies.

3. Create a JavaScript file for your server:Create a JavaScript file for your server:

touch app. js

4. Write a basic Node. js server:
Open `app. js` in your text editor and add the following code:js` in your text editor and add the following code:

const http = require(‘http’);

const hostname=’127. 0. 0. 1’;
const port = 3000;

const server = http. createServer((req, res) => {
res. statusCode = 200;
res. setHeader(‘Content-Type’, ‘text/plain’);
res. end(‘Hello World\n’);
});

server. This is how you can write a listener which listens to a particular port and host name on which your application is hosting.
console. log(`Server running at http://${hostname}:${port}/`);
});

Here’s what this code does:Here’s what this code does:
– `http` module: Node. javascript has native support of http module which allows to create http server.
– `createServer()`: This method creates a new server object of type HTTP and set a callback function to be called when ever there is a request.
– `res. end()`: This function is responsible for sending the response back to the client and this concludes the response process.

5. Run the server:
In your terminal, run the following command to start the server:In your terminal, run the following command to start the server:

node app. js

You should see the following message in your terminal:You should see the following message in your terminal:

Server running at http://127. 0. 0. 1:3000/

6. Visit the server in your web browser by navigating to `http:The output in this case is shown below://127. 0. 0. 1:3000/`. You ought to see the words ‘Hello World’ on the page.

Understanding Modules in Node. js

Modules are one of the core parts of Node. Here is where we have js, which enables you to develop your code into modules and use it again and again. Node. JS has a native module system that provides you with the possibility to include and export code within different files.

Core Modules: Node. The built in modules that come with js include fs for file system , http for server creation and path for file system path manipulation.

Third-Party Modules: To get more modules, you can use the NPM registry with the install command followed by the name of the module you need.

Creating Your Own Modules: Yes, one can create his or her own modules in Node. js by wrapping the functions or objects which we want to use in one file and than using the `require()` function in another file to use them.

Example of creating and using a custom module:Example of creating and using a custom module:
1. Let’s create a new file named as `greet. js`:

// greet. js
function sayHello(name) {
return `Hello, ${name}! `;
}

module. exports = sayHello;

2. To achieve this, the custom module in the app. js`:

const http = require(‘http’);
const greet = require(‘. /greet’)

Below is the code which define the hostname variable to 127.0.0.1.
const port = 3000;

const server = http. createServer((req, res) => {
res. statusCode = 200;
res. setHeader(‘Content-Type’, ‘text/plain’);
res. end(greet(‘World’));
});

server. To do this, we use the listen() function with the parameters for the port, the hostname, and a callback function that we define as follows:
console. log(`Server running at http://${hostname}:${port}/`);
});

Now, when you visit `http:The author also used the following: //127. 0. 0. For instance, if the page is set to render with a URL of `http://www.example.com/page?zoom=1:3000/` it should show “Hello, World!”

Working with NPM

NPM (Node Package Manager) is one of the most important tool in Node. js ecosystem. It helps to track project’s dependencies, install external libraries and distribute your own libraries and applications.

– Installing a Package: To add a package to your project use command `npm install`. For example, to install the popular Express framework:For example, to install the popular Express framework:

npm install express

– Saving Dependencies: All the installed packages are by default added to the dependencies in your package. json` file. You can also save a package as a dev dependency using `–save-dev`:You can also save a package as a dev dependency using `–save-dev`:

npm install –save-dev nodemon

– Running Scripts: NPM enables you to sort out your own scripts in the `package. With this, a `package.json` file can be used to run the code by using `npm run`.

Example:

“scripts”: {
“start”: “node app. js”,
“dev”: “nodemon app. js”
}

You can then run `npm start` to start your application or `npm run dev` to start it with nodemon, a tool that restarts the server every time a file changes.

Asynchronous Programming in Node. js

Node. js is designed in a manner that it is non – blocking and asynchronous which is very ideal for operations that involve i/o. Node is based on asynchronous code, so it is essential to learn how to manage such a code. js development.

– Callbacks: This is a very typical structure in Node. js it is a way when a function is passed as an argument to another function and the passed function is called after the process is finished.

Example:

const fs = require(‘fs’);

fs. To read a file, use readFile function as follows: readFile(‘example.txt’, ‘utf8’, (err, data) => {
if (err) throw err;
console. log(data);
});

– Promises: A current approach to execute such an operation whose completion is not dependent on the continuation of the current process. A promise is a value which will be received in the future when the operation completes.

Example:

const fs = require(‘fs’). promises;

fs. readFile(‘example. txt’, ‘utf8’)
. then(data => console. log(data))
. catch(err => console. error(err));

– Async/Await: A coding language that is an extension of promises in order to make working with asynchronous code a bit nicer.

Example:

const fs = require(‘fs’). promises;

async function readFile() {
try {
const data = await fs. readFile(‘example. txt’, ‘utf8’);
console. log(data);
} catch (err) {
console. error(err);
}
}

readFile();

Conclusion

Node. has brought a drastic change in the development of server-side applications and has made it possible to use javascript on both front and backend. Due to its non-blocking and event-driven design it is well suited for the creation of highly performant and scalable web applications. Below are some tips to get started with Node.;Thus, it is possible to achieve a good understanding of the basics of Node. With the knowledge of Node.js and its module system, NPM and the patterns of asynchronous programming you will be prepared to develop powerful and efficient server-side applications. Whether you are developing a basic web server, a live chat application or a comprehensive API, Node. js has the features and the freedom that you require to achieve your goals.

Leave a Comment