Node.js Essentials

Addition Function
====================
const result =  Number(process.argv[2]) + Number(process.argv[3]);
console.log(result);

Working with Timers#1
=========================
setInterval(() => {console.log('TCS');}, 5000);

Working with Timers#2
=========================
setTimeout(() => {console.log('TCS');}, 2000);

Working with Timers#3
=========================
const interval = setInterval(() => {
  console.log('TCS');
}, 2000);

setTimeout(() => {
  clearInterval(interval);
}, 10000);

Working with callback functions
===========================
let sum = 0;
for(let i=0; i<=1000; i++) {
  if( i % 3 == 0 ){
    sum = sum + i;
  }
}

for(let i=0; i<=1000; i++) {
  if( i % 5 == 0 ){
    sum = sum + i;
  }
}
console.log(sum);

read Stream
==========================
const fs = require("fs");
var data = "";
const src = fs.createReadStream('Node-stream-handson/data_file.txt', 'utf8');
src.on('data', chunk => {
  console.log(chunk.length);
} );


copy stream
==========================
const fs = require("fs");
const src = fs.createReadStream('data_file.txt', 'utf8');
src.pipe(
  fs.createWriteStream('new_data_file.txt')
  );
  
Explore Modules
==========================
var module = require('./module');
var App = require('./App');
const readline = require('readline');
const rs = fs.createReadStream('./input.csv');
//writestreamを作成
const ws = fs.createWriteStream('./output.csv');

const rl = readline.createInterface({
//読み込みたいストリームの設定
  input: rs,
//書き出したいストリームの設定
  output: ws
});



Events - file systems
=============================
const fs = require("fs");
fs.mkdir('Node_folder', (err) => {
    if (err) { throw err; }
    console.log('testディレクトリが作成されました');
});

// 書き込むデータ準備
const data = "This is Node.js a powerful backend javascript used very widely in industry for developing web applications.";

// 書き込み
fs.writeFile("Node_folder/sample.txt", data, (err) => {
  if (err) throw err;
  console.log('正常に書き込みが完了しました');
});

Events - http module
==========================
var http = require('http');
 
var server = http.createServer(function(request, response) {
    response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
    response.end('Hello world');
})

App build - Server Setup
========================
var http = require('http');
var html = require('fs').readFileSync('Sample.html');
 
var server = http.createServer(function(request, response) {
    response.writeHead(200, {'Content-Type': 'text/html'});
    response.end('Hello World');
})
 
server.listen(8000);

App build - Routing
==========================
const http = require('http');
var url = require('url');
const server = http.createServer((req, res) => {
  var pathname = url.parse(request.url).pathname;
  if( pathname == '/hi' ){
    res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
    res.write('Hi Welcome');
    res.end();
  } else if( pathname == '/hello' ) {
    
    res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
    res.write('Hello Buddy');
    res.end();
  } else {
    
    res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' });
    res.write('404 Page not Found');
    res.end();
  }

});

const port = 8000;
server.listen(port);

App build - Routing2
==========================
const http = require('http');
var url = require('url');
const server = http.createServer((req, res) => {
  var pathname = url.parse(request.url).pathname;
  if( pathname == '/hi' ){
    res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
    res.write('Hi Welcome');
    res.end();
  } else if( pathname == '/hello' ) {
    
    res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
    res.write('Hello Buddy');
    res.end();
  } else {
    
    res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' });
    res.write('404 File not found error');
    res.end();
  }

});

const port = 8000;
server.listen(port);


App build - Posting Data
==========================
const http = require('http');
var url = require('url');
const server = http.createServer((req, res) => {
  var pathname = url.parse(request.url).pathname;
  if (pathname == '/hi') {
    res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
    res.write('Hi Welcome');
    res.end();
  } else if (pathname == '/hello') {
    res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
    res.write('Hello Buddy');
    res.end();
  } else {
    res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' });
    res.write('404 Page not Found');
    res.end();
  }
});

const port = 8000;
server.listen(port);
var http = require('http');
const querystring = require('querystring');

http
  .createServer(function (req, res) {
    if (req.method === 'POST') {
      res.writeHead(200, { 'Content-Type': 'text/html' });
      var data = '';

      //POSTデータを受けとる
      req
        .on('data', (chunk) => {
          data += chunk;
        })
        .on('end', () => {
          var form = querystring.parse(data);
          res.end(form);
        });
    }
  })
  .listen(8000);

App build - Handling Requests
============================
var server = require('./server.js');
var routers = require('./routers.js');
var handlers = require('./handlers.js');

App build - https request
==============================
// App
const https = require('https');
const fs = require('fs');

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

https
  .get(options, (resp) => {
    let data = '';
    // A chunk of data has been received.
    resp.on('data', (chunk) => {
      data += chunk;
    });

    // The whole response has been received. Print out the result.
    resp.on('end', () => {
      fs.writeFile('Nodejs.html', data, (err) => {console.log(err)});
    });
  })
  .on('error', (err) => {
    console.log('Error: ' + err.message);
  });



Events - Working with Custom Events
==========================
var events = require('events');
var eventEmitter = new events.EventEmitter();

//Create an event handler:
var Myfunc = function () {
  console.log('HI THERE ! HAPPY LEARNING');
}

eventEmitter.on('MyEvent', Myfunc);

eventEmitter.emit('MyEvent');




Events - http module
==========================

var http = require('http');
var html = require('fs').readFileSync('Sample.html');
 
var server = http.createServer(function(request, response) {
    response.writeHead(200, {'Content-Type': 'text/html'});
    response.end(html);
})
 
server.listen(8000);

========================
<!DOCTYPE html>

<html>

<body>

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

<ul>
  <li>Coffee</li>
  
  <li>Tea</li>
  
  <li>Milk</li>
  
</ul>

<body>


<html>

Read Stream
============================
var fs = require('fs');
var stream;
readerStream = fs.createReadStream('data_file.txt');

readerStream.setEncoding('UTF8');
readerStream.on('data', (chunk) => {
  console.log(chunk.length);
});


Palindrome
============================
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());

Evenly divisible number
============================
function findFactor(n, max) {
  for (let i = 2; i <= max; i++) {
    if (n % i !== 0) return false;
  }
  return true;
}
let n = 20;
//measuring performance
for (let i = n; true; i += n) {
  if (findFactor(i, n)) {
    console.log(i);
    break;
  } else if (i > 1e10) {
    console.log('Limit');
    break;
  }
}

Fibonacci Series\
===========================
function sumFibs(num) {
  let previous = 0;
  let current = 1;
  let sum = 0;
  let next;

  for(current; current <= num;){
    next = current + previous;
    previous = current;

    if(current % 2 === 0) {
      sum += current;
    }

    current = next;
  }

  return sum;
}

console.log(sumFibs(4000000)); // return 4613732

largest prime factor
============================
var divisor = 2;
var number = 600851475143;
while(number > 1){
    if(number % divisor === 0){ 
        number /= divisor;
    } else {
        divisor++;
    }
}
console.log(divisor); // the largest prime factor of 600851475143

Sum of Squares
===========================
const sumSquareDifference = (n) => {
  const numbers = [...Array(n + 1).keys()];
  const sumOfSquares = numbers.reduce(
    (accumulator, number) => accumulator + number ** 2
  );
  const squareOfSum =
    numbers.reduce((accumulator, number) => accumulator + number) ** 2;
  return squareOfSum - sumOfSquares;
};
console.log(sumSquareDifference(100));

nth prime number 
=========================
function getPrimes(max) {
  let arr = new Array(max).fill(undefined);
  for (let i = 2; i < max; i++) {
    if (arr[i] === undefined) {
      arr[i] = true;
      for (let j = i + i; j < max; j += i) {
        arr[j] = false;
      }
    }
  }
  return arr.map((item, i) => (item ? i : false)).filter(Boolean);
}
let primes = getPrimes(150000);
console.log(primes[10000]);

Pythogorean triplet
========================
for (var a = 1; a < 500; a++) {
  for (var b = a; b < 1000; b++) {
    var c = Math.sqrt(a * a + b * b);
    if (c > b && Number.isInteger(c) && a + b + c == 1000) {
      console.log(a * b * c);
    }
  }
}

=============================
function isPrime(val){

  //test if number is prime
  for(var i=2; i < val; i++){
    if(val % i === 0){
      return false;
    }
  }
  return true;
}

sum Primes
========================
function sumPrimes(num) {
  let arr = Array.from({length: num+1}, (v, k) => k).slice(2); 

let onlyPrimes = arr.filter( (n) => { 
  let m = n-1;
  while (m > 1 && m >= Math.sqrt(n)) { 
    if ((n % m) === 0) 
      return false;
      m--;
  }
    return true;
});
  return onlyPrimes.reduce((a,b) => a+b); 
}

Sum of Multiples
==========================
let sum = 0; 
// loop max range 
const numRange = 1000; 
// common util function for checking multiples
 const isMultiple = (num, mode) => (num % mode ? false : true); 
 // looping over an numbers below 1000 and adding 3 or 5 
 // multiples to sum
  for (let i = 0; i < numRange; i++) { if (isMultiple(i, 3) || isMultiple(i, 5)) sum += i; } 
  // logs the sum of all the multiples of 
  // 3 or 5 below 1000 => 233168
   console.log(sum); 



console.log(sumPrimes(5));

sum Prime
=======================
function sumPrime(x) {
  var array = [], sum=0;
  for (var i=2; i<x; i++) {
      if(typeof array[i] === 'undefined') {
          array[i]=true;
          for(var k = i+i; k<x; k+=i) {
              array[k]=false;
          }
          if (array[i]) {
              sum+=i;
          }
      }
  }
  return sum;
}

console.log(sumPrime(2000000)); // 142913828922