Node.js Get Started

Node.js is an open-source, cross-platform runtime environment built on Chrome’s V8 JavaScript engine. It allows you to execute JavaScript code on the server side, enabling the creation of dynamic and real-time applications. Node.js is particularly well-suited for building applications that require high concurrency and low-latency interactions.

Setting Up Node.js
Before we start coding in Node.js, we need to install it on our machine. Visit the official Node.js website (https://nodejs.org/) to download and install the appropriate version for your operating system. Once installed, you can verify the installation by running the following command in your terminal:

node -v

Creating Your First Node.js Application
Let’s begin by creating a simple “Hello, Node.js!” application. Create a file named ‘app.js’ and open it in your favorite code editor. Add the following code:

//app.js
console.log(“Hello, Node.js!”);

Save the file and navigate to the directory containing app.js using your terminal. Run the following command:

node app.js

You will see the output: “Hello, Node.js!” printed in the terminal.

Working with Modules
Node.js follows the CommonJS module system, allowing you to modularize your code and keep it organized. Let’s create a module that calculates the square of a number. Create a file named ‘math.js’ with the following content:

// math.js
exports.square = function(number) {
return number * number;
};

Now, in your ‘app.js’ file, you can use this module:

// app.js
const math = require(‘./math’);
console.log(math.square(5)); // Output: 25



Asynchronous Programming
Node.js is renowned for its non-blocking, asynchronous nature, which enables it to handle multiple connections simultaneously without blocking the execution of other code. Let’s create an example using the built-in ‘fs’ module to read a file asynchronously:

// app.js
const fs = require(‘fs’);
fs.readFile(‘example.txt’, ‘utf8’, function(err, data) {
if (err) {
console.error(“Error reading the file.”);
return;
}
console.log(data);
});



Creating a Simple HTTP Server
Node.js includes the ‘http’ module, allowing you to create HTTP servers easily. Here’s a basic example of creating a server that responds with “Hello, Node.js!” to all incoming requests:

// server.js
const http = require(‘http’);
const server = http.createServer(function(req, res) {
res.writeHead(200, {‘Content-Type’: ‘text/plain’});
res.end(‘Hello, Node.js!\n’);
});
server.listen(3000, ‘127.0.0.1’);
console.log(‘Server running at http://127.0.0.1:3000/’);


So, Node.js provides a powerful platform for building server-side applications using JavaScript.

In this blog, We covered the basics of Node.js, including setting up the environment, creating a simple application, working with modules, understanding asynchronous programming, and creating a basic HTTP server.