Open In App

Node.js Basics: Back-End Development in MERN Stack

Node.js is an open-source and cross-platform JavaScript runtime environment. It’s a powerful tool suitable for a wide range of projects. Node.js stands out as a game-changer. Imagine using the power of JavaScript not only in your browser but also on the server side.

What is MERN stack?

The MERN Stack is a JavaScript Stack that makes the deployment of full-stack web applications easier and faster. It includes four technologies: MongoDB, Express, React, and Node.js. MERN Stack is designed to simplify the development process and make it smoother.

What is Node?

Node.js is an open-source, cross-platform JavaScript runtime built on Chrome’s V8 JavaScript engine. It allows the creation of scalable Web servers without threading and networking tools using JavaScript and a collection of “modules” that handle various core functionalities. It can make console-based and web-based node.js applications.

Why Node?

Node.js is used to build back-end services like APIs like Web App, Mobile App or Web Server. A Web Server will open a file on the server and return the content to the client. It’s used in production by large companies such as Paypal, Uber, Netflix, Walmart, and so on.Here are some reasons to choose Node.js :-

Key features of Node

Nodejs features

Node Advantages

How NodeJS works?

Node accepts the request from the clients and sends the response, while working with the request node.js handles them with a single thread. To operate I/O operations or requests node.js use the concept of threads. Thread is a sequence of instructions that the server needs to perform. It runs parallel on the server to provide the information to multiple clients. Node.js is an event loop single-threaded language. It can handle concurrent requests with a single thread without blocking it for one request.

How node.js works

Application of NodeJS

NodeJS Ecosystem

Node.js has a vibrant ecosystem with a plethora of libraries, frameworks, and tools. Here are some key components:

Creating a Simple Node Application

Step 1: Create a folder for the project using the following command.

mkdir node-basics
cd node-basics

Step 2: Initialize the Node application using the following command.

npm init -y

Step 3: Create a file server.js to create a simple hello program.

touch server.js

Project Structure:

eretg

Folder Structure

Example: Illustration to showcase the basic structure for Node.js

//server.js

const http = require('http');

const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });

    res.write('Hello, World!');

    res.end();
});

server.listen(3000, () => {
    console.log('Server is running on port 3000');
});

Step 4: To start the server run the following command.

node server.js

Output:

First Node app - output

Creating a Simple API

Use Express.js to create API endpoints that handle HTTP requests and responses.

//index.js

const express = require('express');
const app = express();

app.get('/api/hello', (req, res) => {
    res.send('Hello from Node.js!');
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

Output:

Api in Nodejs example - output

Connecting to MongoDB

Use Mongoose to connect your Node.js application to MongoDB and define data models.

const mongoose = require('mongoose');

async function connectToDatabase() {
    try {
        // Connect to MongoDB using the provided connection string
        await mongoose.connect('mongodb://127.0.0.1:27017/myapp', {
            useNewUrlParser: true,
            useUnifiedTopology: true
        });
        console.log("Database Connected");
    } catch (error) {
        console.error("Error connecting to database:", error);
    }
}

connectToDatabase();

// Define the user schema and model 
// after establishing the connection
const Schema = mongoose.Schema;
const userSchema = new Schema({
    name: String,
    email: String,
    age: Number
});

// Create a User model based on the userSchema
const User = mongoose.model('User', userSchema);

// Export the User model to use it elsewhere if needed
module.exports = User;

Output:

Node Database Connection

Conclusion

Node.js is a powerful platform for building scalable and real-time applications, especially in the context of the MERN stack. By understanding Node.js basics, its event-driven architecture, and integration with other technologies like Express.js and MongoDB, developers can leverage its capabilities to create robust back-end systems for modern web applications. Start exploring Node.js today and unlock the full potential of the MERN stack for your projects.

Article Tags :