# Node.Js Essentials Hands-On Solutions from TCS Fresco Play

Q:
Node.Js Essentials Hands-On Solutions from TCS Fresco Play

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

if (err) {

console.error(err)

return

}

console.log(data)

})

var fs = require("fs");

var data = '';

// Set the encoding to be utf8.

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

data += chunk;

console.log(chunk.length);

});

//  console.log(data);

console.log(data.length);

});

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

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.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.write('Welcome Home');

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

res.write('HI TCSer');

}else{

}

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.write('Hi Welcome');

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

res.write('Hello Buddy');

}else{

}

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

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.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) {

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.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) {

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.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) {

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.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

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

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

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

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

})

})

// module.js

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

+1 vote
+1 vote
+1 vote