NodeJS and Introduction

 Here's an introduction to Node.js, Express, MongoDB, and some basic concepts along with examples:


Introduction to Node.js

Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It allows you to run JavaScript on the server side.

Event-driven, non-blocking I/O model: Ideal for building scalable network applications.
Package ecosystem (npm): Largest ecosystem of open source libraries in the world.


Basic Ideas on Node.js

Asynchronous: Node.js is designed for asynchronous operations, meaning it can handle many operations at the same time without waiting for any to complete.

Single-threaded: Uses a single thread to handle requests, but can handle many concurrent connections efficiently due to its event-driven architecture.


Express.js

Express.js is a minimal and flexible Node.js web application framework that provides robust features to build single and multi-page, and hybrid web applications.

Middleware: Functions that execute during the lifecycle of a request to the server.
Routing: Define the endpoints and the HTTP methods (GET, POST, etc.).


MongoDB

MongoDB is a NoSQL database that uses a flexible, JSON-like document structure.
NoSQL Database: Does not use traditional table-based relational database structure.
Document-Oriented: Data is stored in collections as BSON (Binary JSON) documents.


Node.js Installation

To install Node.js:

1. Download the installer from [nodejs.org](https://nodejs.org/).
2. Follow the installer instructions.

To verify installation:
node -v
npm -v


Running a JavaScript File in Node.js

Create a file named `app.js`:

    console.log('Hello, Node.js!');

Run the file:

    node app.js


Server Configuration in Node.js

Create a basic server using the `http` module:

    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.listen(port, hostname, () => {

      console.log(`Server running at http://${hostname}:${port}/`);

    });


Run the server:

node server.js


Examples

Basic Express Server

    const express = require('express');

    const app = express();

    const port = 3000;

    app.get('/', (req, res) => {

      res.send('Hello, Express!');

    });

    app.listen(port, () => {

      console.log(`Example app listening at http://localhost:${port}`);

    });


Connecting to MongoDB

Using `mongoose` to connect to MongoDB:

    const mongoose = require('mongoose');

    mongoose.connect('mongodb://localhost:27017/mydatabase', {useNewUrlParser: true,     useUnifiedTopology: true});

    const db = mongoose.connection;

    db.on('error', console.error.bind(console, 'connection error:'));

    db.once('open', function() {

      console.log('Connected to MongoDB');

    });


npm Modules

npm (Node Package Manager) is used to manage packages.

Install a package: `npm install package-name`

Install globally: `npm install -g package-name`

Save to dependencies: `npm install package-name --save`


HTTP Module

Basic example using the `http` module:

const http = require('http');

const server = http.createServer((req, res) => {

  if (req.method === 'GET' && req.url === '/') {

    res.writeHead(200, { 'Content-Type': 'text/plain' });

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

  } else {

    res.writeHead(404, { 'Content-Type': 'text/plain' });

    res.end('Not Found');

  }

});

server.listen(3000, () => {

  console.log('Server listening on port 3000');

});


Summary

Node.js: JavaScript runtime for server-side programming.

Express.js: Web framework for Node.js.

MongoDB: NoSQL database.

npm: Package manager for Node.js.


--------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------

Server.js

const http=require('http');

const port=4000;

const server=http.createServer((req,res)=>{
    res.writeHead(200,{'Content-Type': 'text/html'});
    res.write(`<ul><li>hello express </li><li>hello php</li></ul>`);
    res.write('<h3>Thank You have a nice day!</h3>')
    res.end();
})

server.listen(port,()=>{
    console.log(`server is running in the port ${port}`)
})


Test.js

var arr=["kolkata","delhi","howrah","punjab","dumdum","patna"]; 

arr.forEach((val)=>{
    console.log(val+"-----"+val.length);
})


Test2.js


var arr=[1,2,3,4,5,6,7,8,9,10]

var result=arr.map((val)=>{
    return val*val;
})

console.log(result);




Comments