Header Ads

Header ADS

Node js Learning


1.User take input and read output:

const readline = require('readline')
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question("please enter your name: ", (name)=>{
    console.log("you entered = " + name);
rl.close(); //to use it for close prompt
});

//use below code to call event during read output
rl.on('close',()=>{
    console.log('interface closed');
    process.exit(0);
})


//Output
please enter your name: zakir you entered = zakir
interface closed  

2. Reading & Writing files synchronously in Node js:-

const readline = require('readline')
const fs       = require('fs')

let txtIn = fs.readFileSync('./files/input.txt', 'utf-8');
console.log(txtIn);

//write text
let content = `data read from input.txt ${txtIn}. \n
Date created ${new Date()}`;
fs.writeFileSync('./files/output.txt',content);

Output: this is a sample text file.

//output.txt file text,

data read from input.txt:  this is a sample text file.. 
 Date created Wed Feb 12 2025 00:04:02 GMT+0600 (Bangladesh Standard Time)

3.Creating a simple web server in Node js:

First way:-
var http = require('http')

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('Hello World!');
  }).listen(8000);


http://127.0.0.1:8000/

Second way:-

const { createServer } = require('node:http');
const hostname = '127.0.0.1';
const port = 3000;
const server = createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World');
});
server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Server running at http://127.0.0.1:3000/

4.Creating Routes in Node JS:-
//====================path check=======================
const { createServer } = require('node:http');
var url = require('url');
const hostname = '127.0.0.1';
const port = 3000;
const server = createServer((req, res) => {
  let path = req.url;
  res.end(path);  //path check

});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

// multiple route url set for different page,

const { createServer } = require('node:http');
var url = require('url');
const hostname = '127.0.0.1';
const port = 3000;
const server = createServer((req, res) => {
  let path = req.url;
 
  if(path === '/' || path.toLocaleLowerCase() === '/home'){
    res.end('you are in home page');
  }else if(path.toLocaleLowerCase() === '/about'){
    res.end('you are in about us page');
  }else if(path.toLocaleLowerCase() === '/contact'){
    res.end('you are in contact page');
  }else{
    res.end('page not found');
//when url not match any path, then display this text
  }

});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

5.Sending HTML Response in Node JS:-

const fs = require('node:fs');
const { createServer } = require('node:http');
var url = require('url');
const hostname = '127.0.0.1';
const port = 3000;

const html = fs.readFileSync('./templates/index.html', 'utf-8');
const server = createServer((req, res) => {
  let path = req.url;

  if(path === '/' || path.toLocaleLowerCase() === '/home'){
    res.end(html.replace('{{%CONTENT%}}','you are in home page'));
  }else if(path.toLocaleLowerCase() === '/about'){
    res.end(html.replace('{{%CONTENT%}}','you are in about page'));
  }else if(path.toLocaleLowerCase() === '/contact'){
    res.end(html.replace('{{%CONTENT%}}','you are in contact page'));
  }else{
    res.end(html.replace('{{%CONTENT%}}','page not found'));  
   
  }
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

//index.html code,
 <div class="main-content">
            <div class="navbar">
                <a href="Home">Home</a>
                <a href="Products">Products</a>
                <a href="About">About</a>
                <a href="Contact">Contact</a>
            </div>
            <div class="page-content">
                <h3>{{%CONTENT%}}</h3>
            </div>
 </div>

6.Setting headers for Response in Node JS:-

const fs = require('node:fs');
const { createServer } = require('node:http');
var url = require('url');
const hostname = '127.0.0.1';
const port = 3000;

const html = fs.readFileSync('./templates/index.html', 'utf-8');
const server = createServer((req, res) => {
  let path = req.url;

  if(path === '/' || path.toLocaleLowerCase() === '/home'){
    res.writeHead(200,{
      'Content-Type': 'text/html', //header response
    });
    res.end(html.replace('{{%CONTENT%}}','you are in home page'));
  }else if(path.toLocaleLowerCase() === '/about'){
    res.writeHead(200);
    res.end(html.replace('{{%CONTENT%}}','you are in about page'));
  }else if(path.toLocaleLowerCase() === '/contact'){
    res.writeHead(200);
    res.end(html.replace('{{%CONTENT%}}','you are in contact page'));
  }else{
    res.writeHead(404);
    res.end(html.replace('{{%CONTENT%}}','page not found'));  
   
  }
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

7.Working with JSON data:-

















No comments

Theme images by fpm. Powered by Blogger.