in NodeJS Essentials by
Node.Js Essentials Hands-On Solutions from TCS Fresco Play

2 Answers

0 votes
by

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);

0 votes
by

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);

...