Node.Js Essentials Hands-On Solutions | TCS Fresco Play

62

Disclaimer: The primary purpose of providing this solution is to assist and support anyone who are unable to complete these courses due to a technical issue or a lack of expertise. This website's information or data are solely for the purpose of knowledge and education.

Make an effort to understand these solutions and apply them to your Hands-On difficulties. (It is not advisable that copy and paste these solutions).

All Question of the Hands-On Present Below for Ease Use Ctrl + F with the question name to find the Question. All the Best!


1. Fibonacci Series


Path: NodeJs/Node Js Essentials/fibonacci-series/fibonacci.js

let n1 = 0, n2 = 1, nextTerm;

let s = 0;

for (let i = 1; n1 <= 4000000; i++) {

    if(n1 % 2 == 0){

      s += n1

    }

    nextTerm = n1 + n2;

    n1 = n2;

    n2 = nextTerm;

}

console.log(s);


2. Largest  Prime Factor

Path: NodeJs/Node Js Essentials/largest-prime-factor/app.js

var divisor = 2;

var number = 600851475143;

while(number > 1){

    if(number % divisor === 0){ 

        number /= divisor;

    } else {

        divisor++;

    }

}

console.log(divisor);


3. Palindrome 

Path: NodeJs/Node Js Essentials/palindrome/palindrome.js

function largestPalindrome(){

   var arr = [];    

    for(var i =999; i>100; i--){

        for(var j = 999; j>100; j--){

            var mul = j*i;

            if(isPalin(mul)){

                arr.push(j * i);

            }

        }

    }

    return Math.max.apply(Math, arr);

}

function isPalin(i){

    return i.toString() == i.toString().split("").reverse().join("");

}

console.log(largestPalindrome());


4. Evenly Divisible

Path: NodeJs/Node Js Essentials/evenly-divisible/divisible.js

function gcd(a, b)

{

   if(a%b != 0)

      return gcd(b,a%b);

   else

      return b;

// Function returns the lcm of first n numbers

function lcm(n)

{

    let ans = 1;   

    for (let i = 1; i <= n; i++)

        ans = (ans * i)/(gcd(ans, i));

    return ans;

}       

// function call     

    let n = 20;

    console.log(lcm(n));


5. Sum of Squares

Path : NodeJs/Node Js Essentials/sum-of-squares/App.js

let sum = 0, sum_sq = 0;

for (let i = 1; i <= 100; i++){

  sum += i;

  sum_sq += i*i;

}

console.log(Math.abs(sum_sq - sum*sum))


6. Nth Prime Number

Path: NodeJs/Node Js Essentials/neth-prime/App.js

const findPrime = num => {

   let i, primes = [2, 3], n = 5;

   const isPrime = n => {

      let i = 1, p = primes[i],

      limit = Math.ceil(Math.sqrt(n));

      while (p <= limit) {

         if (n % p === 0) {

            return false;

         }

         i += 1;

         p = primes[i];

      }

      return true;

   }

   for (i = 2; i <= num; i += 1) {

      while (!isPrime(n)) {

         n += 2;

      }

      primes.push(n);

      n += 2;

   };

   return primes[num - 1];

}

console.log(findPrime(10001));


7. Pythagorean Triplets

Path: NodeJs/Node Js Essentials/pythagorean-triplets/App.js

function findProd() {

  for (let i = 1; i <= 1000; i++) {

    for (let j = 1; j <= 1000; j++) {

      const k = 1000 - i - j;

      if (i * i + j * j == k * k) {

        return i * j * k;

      }

    }

  }

}

console.log(findProd())


8. Sum of Primes

Path: NodeJs/Node Js Essentials/sum-of-primes/App.js

const isPrime = num => {

    for(let i = 2, s = Math.sqrt(num); i <= s; i++)

        if(num % i === 0) return false; 

    return num > 1;

}

let sum = 0;

for(let i=2; i < 2000000; i++){

  if(isPrime(i)){

    sum += i;

  }

console.log(sum)


9. Sum of Multiples

Path: NodeJs/Node Js Essentials/sum-of-multiples/App.js

var sum = 0;

var number = 1000;

for (var i = 0; i < number; i++) {

    if (i % 3 == 0 || i % 5 == 0) {

        sum += i;

    }

}

console.log(sum);


10. Events Working With Files

Path: NodeJs/Node Js Essentials/events-working-with-files/App.js

const fs = require('fs')

fs.readFile('To_Read.txt', 'utf8' , (err, data) => {

  if (err) {

    console.error(err)

    return

  }

  console.log(data)

})


11. Stream Reading Files

Path: NodeJs/Node Js Essentials/stream-reading-files/app.js

var fs = require("fs");

var data = '';

// Create a readable stream

var readerStream = fs.createReadStream('Node-stream-handson/data_file.txt');

// Set the encoding to be utf8. 

readerStream.setEncoding('UTF8');

// Handle stream events --> data, end, and error

readerStream.on('data', function(chunk) {

   data += chunk;

   console.log(chunk.length);

});

readerStream.on('end',function() {

  //  console.log(data);

   console.log(data.length);

});

readerStream.on('error', function(err) {

   console.log(err.stack);

});

console.log("Program Ended");


12. Stream Writing Files

Path: NodeJs/Node Js Essentials/stream-writing-files/App.js

var fs = require("fs");

var data = 'Node.js is an ultimate backend javascript for backend developement';

// Create a writable stream

var writerStream = fs.createWriteStream('Big_data.txt');

for (let i = 0; i < 10 ^ 5; i++) {

  writerStream.write(data, 'UTF8');

}

// Mark the end of file

writerStream.end();

// Handle stream events --> finish, and error

writerStream.on('finish', function () {

  console.log("Write completed.");

});

writerStream.on('error', function (err) {

  console.log(err.stack);

});


13. Stream File Copy

Path: NodeJs/Node Js Essentials/stream-file-copy/App.js

var fs = require("fs");

// Create a readable stream

var readerStream = fs.createReadStream('data_file.txt');

// Create a writable stream

var writerStream = fs.createWriteStream('new_data_file.txt');

// Pipe the read and write operations

// read input.txt and write data to output.txt

readerStream.pipe(writerStream);


14. App Build Posting Data

Path: NodeJs/Node Js Essentials/app-build-posting-data/server.js

const http = require('http');

const url = require('url');

const fs = require('fs');

const querystring = require('querystring');

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

  const urlparse = url.parse(req.url, true);

  if (urlparse.pathname == '/' && req.method == 'POST') {

    req.on('data', data => {

      const jsondata = JSON.parse(data);

      fs.writeFile('output.txt', data, err => {

        if (err) {

          console.error(err)

          return

        }

      })

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

      res.end(JSON.stringify(projects, null, 2));

    });

  }

});

server.listen(8000);

Path: NodeJs/Node Js Essentials/app-build-routing-2/server.js

const http = require('http');

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

   const url = req.url;

   if(url === '/hi'){

     res.writeHead(200);

      res.write('Welcome Home');

   }else if (url === '/hello'){

      res.write('HI TCSer');

     res.writeHead(200);

   }else{

      res.write('404 File not found error');

     res.writeHead(404);

   }   

      return res.end();

});

server.listen(3000);


Path: NodeJs/Node Js Essentials/app-build-routing/router.js

#!/bin/bash

SCORE=0

PASS=0

fail=0

TOTAL_TESTS=1

TEST_1=$( cat router.js | grep -e "createServer" -e "res.writeHead" -e "Hi TCSer" -e "Hi Welcome" -e "Hello Buddy" | wc -l )

if [ $TEST_1 -ge 5 ]

then PASS=$((PASS + 1))

fi;

echo "Total testcases: 1"

echo "Total testcase passed: $PASS"

echo "Total testcase fail: $fail"

SCORE=$(($PASS*100 / $TOTAL_TESTS))

echo "FS_SCORE:$SCORE%"


Path: NodeJs/Node Js Essentials/app-build-server-setup/server.js

const http = require('http');

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

   const url = req.url;

   if(url === '/hi'){

     res.writeHead(200);

      res.write('Hi Welcome');

   }else if (url === '/hello'){

      res.write('Hello Buddy');

     res.writeHead(200);

   }else{

      res.write('404 File not found error');

     res.writeHead(404);

   }   

      return res.end();

});

server.listen(3000);


15. Events HTTP Module

Path: NodeJs/Node Js Essentials/events-http-module/app.js

const http = require('http');

const fs = require('fs')

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

fs.readFile('sample.html', 'utf8' , (err, data) => {

  if (err) {

    console.error(err)

    return

  }

  res.write(data);

  res.end();

})

});

server.listen(8000);


Path: NodeJs/Node Js Essentials/events-http-module/sample.html

<!DOCTYPE html>

    <html lang="en">

    <body>

        <h2>Welcome ! what would oyu like to have</h2>

        <ul>

            <li>Cofee</li>

            <li>Tea</li>

            <li>Milk</li>

        </ul>

    </body>

    </html>


Path: NodeJs/Node Js Essentials/events-simple-http-module/app.js

const http = require('http');

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

  res.write('Hello World');

  res.end();

})

});

server.listen(8000);


Path: NodeJs/Node Js Essentials/events-working-with-custom-events/app.js

var events = require('events');

var eventEmitter = new events.EventEmitter();

//Create an event handler:

var Myfunc = function () {

  console.log('HI THERE ! HAPPY LEARNING');

}

//Assign the event handler to an event:

eventEmitter.on('MyEvent', Myfunc);

//Fire the 'scream' event:

eventEmitter.emit('MyEvent');


16. Handling Requests

Path: NodeJs/Node Js Essentials/handling-requests/App.js

var http = require('http');  

// Create a server object

http.createServer(function (req, res) {     

    // http header

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

    var url = req.url;     

    if(url ==='/') {

        res.write(`

        <form method="post" action="submit">

        <input type=text name=first>

        <input type=text name=first>

        <button>Submit</button>

        </form>        

        `); 

        res.end(); 

    }

    else if(url ==='/contact') {

        res.write(' Welcome to contact us page'); 

        res.end(); 

    }

    else {

        res.write('Hello World!'); 

        res.end(); 

    }

}).listen(3000, function() {    

    // The server object listens on port 3000

    console.log("server start at port 3000");

});


Path: NodeJs/Node Js Essentials/handling-requests/handlers.js

var http = require('http');  

// Create a server object

http.createServer(function (req, res) {      

    // http header

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

    var url = req.url;      

    if(url ==='/') {

        res.write(`

        <form method="post" action="submit">

        <input type=text name=first>

        <input type=text name=first>

        <button>Submit</button>

        </form>      

        `); 

        res.end(); 

    }

    else if(url ==='/contact') {

        res.write(' Welcome to contact us page'); 

        res.end(); 

    }

    else {

        res.write('Hello World!'); 

        res.end(); 

    }

}).listen(3000, function() {      

    // The server object listens on port 3000

    console.log("server start at port 3000");

});


Path: NodeJs/Node Js Essentials/handling-requests/routers.js

var http = require('http');  

// Create a server object

http.createServer(function (req, res) {      

    // http header

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

    var url = req.url;      

    if(url ==='/') {

        res.write(`

        <form method="post" action="submit">

        <input type=text name=first>

        <input type=text name=first>

        <button>Submit</button>

        </form>        

        `); 

        res.end(); 

    }

    else if(url ==='/contact') {

        res.write(' Welcome to contact us page'); 

        res.end(); 

    }

    else {

        res.write('Hello World!'); 

        res.end(); 

    }

}).listen(3000, function() {    

    // The server object listens on port 3000

    console.log("server start at port 3000");

});


Path: NodeJs/Node Js Essentials/handling-requests/server.js

var http = require('http');  

// Create a server object

http.createServer(function (req, res) {      

    // http header

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

    var url = req.url;

    if(url ==='/') {

        res.write(`

        <form method="post" action="submit">

        <input type=text name=first>

        <input type=text name=first>

        <button>Submit</button>

        </form>   

        `); 

        res.end(); 

    }

    else if(url ==='/contact') {

        res.write(' Welcome to contact us page'); 

        res.end(); 

    }

    else {

        res.write('Hello World!'); 

        res.end(); 

    }

}).listen(3000, function() {

    // The server object listens on port 3000

    console.log("server start at port 3000");

});


17. Https Requests

Path: NodeJs/Node Js Essentials/https-requests/app.js

const https = require('https')

const options = {

  hostname: 'en.wikipedia.org',

  port: 443,

  path: '/dwiki/Nodejs',

  method: 'GET'

}

const req = https.request(options, res => {

  console.log(`statusCode: ${res.statusCode}`)

  res.on('data', d => {

    process.stdout.write(d)

  })

})

req.on('error', error => {

  console.error(error)

})

req.end()



Extras

18. Addition

Path: NodeJs/Node Js Essentials/addition.js

console.log(parseInt(process.argv[2])+parseInt(process.argv[3]));


19. Callback

Path: NodeJs/Node Js Essentials/callback.js

let sum=0;

for(let i=3; i<=1000; i++){

    if(i%3==0){

        sum += i

    }

    if(i%5==0){

        sum+=i

    }

}

setTimeout(()=>console.log(sum), 1000);


20. Module

Path: NodeJs/Node Js Essentials/module.js

// app.js

const m = require('./module');

const readline = require('readline');

let r1 = readline.createInterface(process.stdin, process.stdout);

r1.question("first number", n1 =>{

  r1.question("second number", n2 =>{

    console.log(m.add(n1,n2));

    console.log(m.multiply(n1,n2));

  })

})

// module.js

module.exports.add = (a,b) => {

    return a+b;

}

module.exports.multiply = (a,b)=>{

    return a+b

}


20. Timer 1

Path: NodeJs/Node Js Essentials/timer1.js

function print(){

    console.log("TCS");

}


setInterval(print, 5000);


21. Timer 2

Path: NodeJs/Node Js Essentials/timer2.js

function print(){

    console.log("TCS");

}

setTimeout(print, 2000);


22. Timer 3

Path: NodeJs/Node Js Essentials/timer3.js

function print(){

    console.log("TCS");

}

function stop(){

    clearInterval(t)

}

const t = setInterval(print, 2000);

setTimeout(stop, 10000);



If you have any queries, please feel free to ask on the comment section.

If you want MCQs and Hands-On solutions for any courses, Please feel free to ask on the comment section too.

Please share and support our page!

Post a Comment

62Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
  1. want remaining answers too

    ReplyDelete
  2. Please search it on GitHub or visit below link
    https://github.com/csrohit/fresco-play/tree/main/NodeJs/Node%20Js%20Essentials

    ReplyDelete
    Replies
    1. Hello sir; Q10) Events working with files is not running successfully, could you please check and also I want the source code of R basics as well where will I find that?

      Delete
  3. process.stdin.resume();
    process.stdin.setEncoding("ascii");
    _input = "";
    process.stdin.on("data", function (input) {
    _input += input;
    });

    process.stdin.on("end", function () {
    logString(_input);
    });


    function logString(stringToLog) {
    setTimeout(info, 0, stringToLog);
    setTimeout(log, 800, stringToLog);
    setTimeout(log, 1300, stringToLog);
    setTimeout(log, 1800, stringToLog);
    setTimeout(log, 2300, stringToLog);
    setTimeout(log, 2800, stringToLog);
    }

    function log(stringToLog){
    console.log(stringToLog);
    }

    function info(stringToLog){
    console.log("Logging "+ stringToLog +" every 0.5 seconds");
    }

    ReplyDelete
  4. why above ans is wrong for qn working with timer qn

    ReplyDelete
    Replies
    1. Please search it on GitHub or visit below link
      https://github.com/csrohit/fresco-play/tree/main/NodeJs/Node%20Js%20Essentials

      Delete
  5. function logString(stringToLog) {
    //Enter your code here
    console.log("Logging "+ stringToLog +" every 0.5 seconds");

    }

    function print(input){

    console.log(input);

    }

    function stop(){

    clearInterval(t)

    }

    const t = setInterval(print, 500,_input);
    setTimeout(stop, 3000);

    ReplyDelete
    Replies
    1. No test cases passed with this code

      Delete
    2. function logString(stringToLog) {
      console.log("Logging "+ stringToLog +" every 0.5 seconds");
      }
      function print(input){
      console.log(_input);
      }
      function stop(){
      clearInterval(t)
      }
      const t = setInterval(print, 500,_input);
      setTimeout(stop, 3000);

      Delete

  6. Callbacks and events


    process.stdin.on("end", function () {

    const EventEmitter=require('events');
    let data=input.split(" ");
    n1=data[0];
    n2=data[1];
    // console.log(n1,n2);

    let result=0;
    const sum=()=>{
    for(let i=0;i<=1000;i++)
    {
    if(i%n1==0)
    {
    result+=i;
    }
    }
    for(let j=0;j<=1000;j++)
    {
    if(j%n2==0)
    {
    result+=j;
    }
    }
    console.log(result);
    }
    setTimeout(sum,2000);

    const event=new EventEmitter();

    event.on("MyEvent",()=>{
    console.log(`Multiples of ${n1} & ${n2}`);
    })
    event.emit("MyEvent");



    });

    ReplyDelete
    Replies
    1. Hey bro, app calculator have you done?? Mine 50%test case passes. Have you done??

      Delete
  7. process.stdin.on("end", function () {
    //write your code within the function
    input = input.replace(/\W/g, '').toLowerCase();
    var result = (input.toString() == input.toString().split("").reverse().join(""));
    console.log(result);
    });

    ReplyDelete
  8. Answer for App Routing - Simple Calculator ?

    ReplyDelete
    Replies
    1. Have you got the answer?

      Delete
    2. If you got the answer please post here.

      Delete
    3. Hi, If you have code of 'module and file system' and 'timer' then pls post here

      Delete
    4. const http = require("http");
      const url = require("url");

      const funcMap = {
      add: (a, b) => {
      return `Addition is: ${a + b}`;
      },
      subtract: (a, b) => {
      return `Subtraction is: ${a - b}`;
      },
      multiple: (a, b) => {
      return `Multiplication is: ${a * b}`;
      },
      div: (a, b) => {
      return `Division is: ${a / b}`;
      },
      };
      http.createServer((req, response) => {
      response.writeHead(200, {
      "Content-Type": "text/html"
      });
      req.setEncoding("utf-8");
      let urlhandler = url.parse(req.url, true);
      let pathname = urlhandler.pathname;
      let {
      func,
      a,
      b
      } = urlhandler.query;
      if (pathname === "/cal") {
      if (func == undefined) {
      response.write(funcMap["div"](+a, +b));
      } else {
      response.write(funcMap[func](+a, +b));
      }
      }
      response.end();
      })
      .listen(8000);

      Delete
    5. Above code works in local, but still test cases are failing in the hackerank. What did you do apart from this code?

      Delete
  9. Answer for Try It Out - Sort and Search Products

    ReplyDelete
  10. Any one who completed the AngularJS 1.x Directives course on fresco

    Plz give the solution for sort and search

    ReplyDelete
  11. can anyone send me events working with files code? please

    ReplyDelete
    Replies
    1. did you get the answer for above question? If so please paste solution here

      Delete
  12. Can anyone please post the correct code for 'events - working with files' and 'app build' ? I am stuck from a long time. (Thanks in advance)

    ReplyDelete
  13. Github link given by admin not working

    ReplyDelete
  14. modules and file system answer plzz..

    ReplyDelete
    Replies
    1. Here are the instructions for this exercise. I haven't resolved it yet.
      app.js
      --------------------------------------
      //import the 'fs' and 'maths.js' module
      //read the content of 'input.txt' file and copy the content to 'duplicate.txt' file
      //call the 'sum and 'multiply' functions of maths module and store the return values in 'result' and 'product' variables
      //write the content 'The sum of the numbers is: result. The product of the numbers is: product' to the 'output.txt' file

      math.js
      -----------------------------------------
      // Create and export a module with two functions sum and multiply
      // Both functions should two arguements and return the sum and product values

      Delete
  15. can anyone help me with the developers git .. got branch and merge conflicts hands pn t be completed..

    ReplyDelete
  16. im stucked with an exercise, have some solved?
    the instructions are the following:

    app.js
    --------------------------------------
    //import the 'fs' and 'maths.js' module
    //read the content of 'input.txt' file and copy the content to 'duplicate.txt' file
    //call the 'sum and 'multiply' functions of maths module and store the return values in 'result' and 'product' variables
    //write the content 'The sum of the numbers is: result. The product of the numbers is: product' to the 'output.txt' file

    math.js
    -----------------------------------------
    // Create and export a module with two functions sum and multiply
    // Both functions should two arguements and return the sum and product values

    ReplyDelete
    Replies
    1. App.js

      ==========

      const fs = require("fs");
      var calculator = require('./maths');

      var readerStream = fs.createReadStream('input.txt');
      var writerStream = fs.createWriteStream('duplicate.txt');
      readerStream.pipe(writerStream);


      var a=10, b=5;

      var result = 'The sum of the numbers is:' + calculator.add(a,b) + '. ';
      var product = 'The product of the numbers is:' + calculator.multiply(a,b);

      let data = result + product;
      var writerStream = fs.createWriteStream('output.txt');
      writerStream.write(data, 'UTF8');
      writerStream.end();


      Maths.js

      exports.add = function (a, b) {
      return a+b;
      };
      exports.multiply = function (a, b) {
      return a*b;
      };

      Delete
    2. I am getting this error.................
      plz help.

      npm WARN ws@7.4.6 requires a peer of bufferutil@^4.0.1 but none is installed. You must install peer dependencies yourself.

      npm WARN ws@7.4.6 requires a peer of utf-8-validate@^5.0.2 but none is installed. You must install peer dependencies yourself.

      npm WARN file-handling-nodejs@1.0.0 No description

      npm WARN file-handling-nodejs@1.0.0 No repository field.

      audited 296 packages in 1.999s

      found 0 vulnerabilities

      > file-handling-nodejs@1.0.0 test /projects/challenge

      > mocha --reporter mocha-junit-reporter

      /projects/challenge/node_modules/yargs-parser/build/index.cjs:991

      throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`);

      ^

      Error: yargs parser supports a minimum Node.js version of 10. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions

      at Object. (/projects/challenge/node_modules/yargs-parser/build/index.cjs:991:15)

      at Module._compile (module.js:653:30)

      at Object.Module._extensions..js (module.js:664:10)

      at Module.load (module.js:566:32)

      at tryModuleLoad (module.js:506:12)

      at Function.Module._load (module.js:498:3)

      at Module.require (module.js:597:17)

      at require (internal/module.js:11:18)

      at Object. (/projects/challenge/node_modules/mocha/lib/cli/options.js:12:21)

      at Module._compile (module.js:653:30)

      npm ERR! code ELIFECYCLE

      npm ERR! errno 1

      npm ERR! file-handling-nodejs@1.0.0 test: `mocha --reporter mocha-junit-reporter`

      npm ERR! Exit status 1

      npm ERR!

      npm ERR! Failed at the file-handling-nodejs@1.0.0 test script.

      npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

      npm ERR! A complete log of this run can be found in:

      npm ERR! /home/user/.npm/_logs/2022-02-23T08_30_04_119Z-debug.log

      Delete
  17. Please provide solution events working with file

    ReplyDelete
  18. can anyone help with the solution for
    Events- working with files
    hands on-1 more on node.js (testing-palindrome)
    App build-simple calculator

    ReplyDelete
    Replies
    1. Palindrome --->>>>

      process.stdin.resume();
      process.stdin.setEncoding("ascii");
      var input = "";
      process.stdin.on("data", function (chunk) {
      input += chunk;
      });


      process.stdin.on("end", function () {
      //write your code within the function
      let input1 = input.toLowerCase();
      let ans = checkPalindrome(input1);
      //condition checking ans is true or not
      if( ans == true )
      {
      console.log("true");
      }
      else
      {
      console.log("false");
      }

      });

      // program to check if the string is palindrome or not

      function checkPalindrome(string) {

      // find the length of a string
      const len = string.length;

      // loop through half of the string
      for (let i = 0; i < len / 2; i++) {

      // check if first and last string are same
      if (string[i] !== string[len - 1 - i]) {
      return false;
      }
      }
      return true;
      }

      Delete
  19. Events - Working with files
    Streams - Reading Files
    Hands-on 1: More on node.js
    Streams - Write to File
    Hands-on 2: More on node.js
    answer pls

    ReplyDelete
  20. Please provide answers of nodejs with frame work (2 hands on are there) thanks

    ReplyDelete
  21. ## Palindrome

    process.stdin.resume();
    process.stdin.setEncoding("ascii");
    var input = "";
    process.stdin.on("data", function (chunk) {
    input += chunk;
    });


    process.stdin.on("end", function () {
    //write your code within the function
    let input1 = input.toLowerCase();
    let ans = checkPalindrome(input1);
    //condition checking ans is true or not
    if( ans == true )
    {
    console.log("true");
    }
    else
    {
    console.log("false");
    }

    });

    // program to check if the string is palindrome or not

    function checkPalindrome(string) {

    // find the length of a string
    const len = string.length;

    // loop through half of the string
    for (let i = 0; i < len / 2; i++) {

    // check if first and last string are same
    if (string[i] !== string[len - 1 - i]) {
    return false;
    }
    }
    return true;
    }


    #################################################################

    ## Largest Prime Factor

    process.stdin.resume();
    process.stdin.setEncoding("ascii");
    var input = "";
    process.stdin.on("data", function (chunk) {
    input += chunk;
    });


    process.stdin.on("end", function () {
    //write your code within the function
    let input1 = input.toLowerCase();
    lpf(input1)

    });

    function lpf(string) {
    var divisor = 2;

    var number = string;

    while(number > 1){

    if(number % divisor === 0){

    number /= divisor;

    } else {

    divisor++;

    }

    }
    console.log(divisor);
    }



    ################################################################

    ## timer

    process.stdin.resume();
    process.stdin.setEncoding("ascii");
    _input = "";
    process.stdin.on("data", function (input) {
    _input += input;
    });

    process.stdin.on("end", function () {
    logString(_input);
    });

    var count = 1
    function logString(stringToLog) {
    //Enter your code here
    console.log("Logging "+ stringToLog +" every 0.5 seconds");

    }

    var interval = setInterval(function(){
    if(count<6){
    console.log(_input);
    count = count+1
    }
    }, 500);

    setTimeout(function() {
    clearInterval(interval);
    }, 3000);


    ##################################################################

    ## callback and events

    process.stdin.resume();
    process.stdin.setEncoding("ascii");
    var input = "";
    process.stdin.on("data", function (chunk) {
    input += chunk;
    });



    process.stdin.on("end", function () {

    const EventEmitter=require('events');
    let data=input.split(" ");
    n1=data[0];
    n2=data[1];
    // console.log(n1,n2);

    let result=0;
    const sum=()=>{
    for(let i=0;i<=1000;i++)
    {
    if(i%n1==0)
    {
    result+=i;
    }
    }
    for(let j=0;j<=1000;j++)
    {
    if(j%n2==0)
    {
    result+=j;
    }
    }
    console.log(result);
    }
    setTimeout(sum,2000);

    const event=new EventEmitter();

    event.on("MyEvent",()=>{
    console.log(`Multiples of ${n1} & ${n2}`);
    })
    event.emit("MyEvent");



    });

    ReplyDelete
  22. Can anyone please share ! Events - Working with files i.e., File system and modules ???

    ReplyDelete
  23. Simple Calculator - Online IDE

    const http = require("http");
    const url = require("url");
    const hostname = 'localhost';
    const port = 8000;

    const funcMap = {
    add: (a, b) => {
    return `Addition is: ${a + b}`;
    },
    subtract: (a, b) => {
    return `Subtraction is: ${a - b}`;
    },
    multiple: (a, b) => {
    return `Multiplication is: ${a * b}`;
    },
    div: (a, b) => {
    return `Division is: ${a / b}`;
    },
    };
    const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/html');
    let urlhandler = url.parse(req.url, true);
    let pathname = urlhandler.pathname;
    let { func, a, b } = urlhandler.query;
    if (pathname === "/cal") {
    if (func == undefined) {
    res.write(funcMap["div"](+a, +b));
    } else {
    res.write(funcMap[func](+a, +b));
    }
    }
    res.end();
    });
    server.listen(port, hostname, () => {
    });

    ReplyDelete
    Replies
    1. Test case not getting pass
      Do we have install something here
      If yes what we have to?
      Share the code for that.
      Thanks in advance

      Delete
    2. var http = require('http');
      const url = require('url');

      const hostname = 'localhost';
      const port = 8000;

      const funcMap = {
      add: (a, b) => {
      return `Addition is: ${a + b}`;
      },
      subtract: (a, b) => {
      return `Subtraction is: ${a - b}`;
      },
      multiple: (a, b) => {
      return `Multiplication is: ${a * b}`;
      },
      div: (a, b) => {
      return `Division is: ${a / b}`;
      },
      };
      const server = http.createServer((req, res) => {
      res.statusCode = 200;
      res.setHeader('Content-Type', 'text/html');
      let urlhandler = url.parse(req.url, true);
      console.log(urlhandler);
      let pathname = urlhandler.pathname;
      let { func, a, b } = urlhandler.query;
      if (pathname === "/cal") {
      if (func == undefined) {
      res.write(funcMap["div"](+a, +b));
      } else {
      res.write(funcMap[func](+a, +b));
      }
      }
      res.end();
      });
      server.listen(port, hostname, () => {
      });

      Open Terminal and run "node App.js" and then "Run Tests", then it will pass all the test cases.

      Delete
  24. Simple Calculator - Online IDE
    Solution is not passing test case.
    Can anyone share the working code.

    ReplyDelete
  25. HTTP_Simple Calculator - Online IDE
    Solution plz

    ReplyDelete
  26. plz send simple calculator and http modules
    anyone??

    ReplyDelete
    Replies
    1. Bro please send modules and filesystem answers

      Delete
  27. modules and file systems hands on pl??

    ReplyDelete
  28. Node.js essentials - Express - Profile management...
    answer anyone have..?

    ReplyDelete
  29. Node.js Essentials - HTTPS modules - Get the wiki page::

    var https = require('https');

    var fs = require('fs');

    var options = {
    hostname : "en.wikipedia.org",
    port : 443,
    path : "/wiki/Nodejs",
    method : "GET"
    };

    var req = https.request(options, function(res){

    var responseBody = "";

    console.log('Response started!');

    console.log(`Server status: ${res.statusCode}`);

    console.log("Response header %j", res.headers);
    res.setEncoding('UTF-8');

    res.once('data', function(chunck){
    console.log(chunck);
    });

    res.on('data', function(chunck){
    console.log(`---chunck --- ${chunck.length}`);
    responseBody+= chunck;
    });

    res.on("end", function(){
    fs.writeFile('Node.html', responseBody, function(err){
    if(err){
    throw err;
    }
    console.log('file downloaded successfully');
    });
    })
    });

    // if there are error on the request

    req.on('error', function(err){
    console.log(`problem with request : ${err.message}`);
    });

    req.end();

    ReplyDelete
    Replies
    1. var options = {
      hostname : "en.wikipedia.org",
      port : 443,
      path : "/wiki/Nodejs",
      method : "GET",
      rejectUnauthorized: false
      };

      Delete
  30. modules and file systems hands on plz?

    ReplyDelete
  31. hello guys can anyone please help me for this hands-on challenge "Build a react application that manages agenda it should helps to add agenda title and topics and view those agenda details this application has buttons [CLICK TO VIEW AGENDA,CLICK TO ADD AGENDA] to switch between agenda form (for adding agenda) and view agenda (for displaying details) and the buttons and form fields must have validation in the hands on so please help me to solve this challenge

    ReplyDelete
  32. Modules_And_FileSystem (Modules and file System) handson answer plz

    ReplyDelete
    Replies
    1. Modules_And_FileSystem (Modules and file System) handson answer;

      app.js


      const fs = require("fs");
      var calculator = require('./maths');

      var readerStream = fs.createReadStream('input.txt');
      var writerStream = fs.createWriteStream('duplicate.txt');
      readerStream.pipe(writerStream);


      var a=10, b=5;

      var result = 'The sum of the numbers is:' + calculator.sum(a,b) + '. ';
      var product = 'The product of the numbers is:' + calculator.multiply(a,b);

      let data = result + product;
      console.log(data);

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

      maths.js


      module.exports.sum = (a,b) => {

      return (+a)+(+b);

      }

      module.exports.multiply = (a,b)=>{

      return a*b

      }


      --------------
      thank me later

      Delete
  33. Please Provide solution for Modules_And_FileSystem. All the above solutions are showing errors. Please help anyone.

    ReplyDelete
Post a Comment

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !