Best JavaScript code snippet using wpt
nodeDebianServerUNL.js
Source:nodeDebianServerUNL.js  
1'use strict'; // is unnecessary inside of modules.2//file:///home/akaarna/react-tutorial/build/index.html3/*4Standard dirs should be:5images6pages7scripts8styles9*/10/*11Can be started as parent in build subdir:12  >node ..\nodeServerUNL.js13*/14let typeProj =  ''; // 'build';15let dirName = 'build'; // React build dir as root dir.16//let dirName = ''; // root dir.17//let methodType = 'get'; // 'post' or 'get' for secure server.18//let formNameIni = 'submitFormAK-Ini';19//let formName = 'submitFormAK';20//let dirName = 'arch'; // root dir21let formNameIni = 'index.html';22//let formNameIni = 'indexForm.html';23// Using special formName  /formAKchk?q=123-12345678-1234567 /formAKval?q=123-12345678-1234567 or /formAKpay?q=xxx24const addon = require('./build/addon');25const http = require('http');26const urlval = 'http://10.8.194.3:9994/'; // project WinTicsCheckNoSslTEST new at 'http://10.8.194.3:9994/'27//let reqString = urlval + '?agent=58&type=2&command=checkval&ticket_number=225-13818091-1101234';28let reqString = urlval + '?agent=58&type=2&command=checkval&ticket_number='; // + search;29const urlpay = 'http://10.8.194.3:10064/'; // project UnlCashExTEST ver. 3.830let reqStringPay; //= urlpay + '?agent=65&type=2&command=pay&date=20200808&txn_id=' + txn_id + '&game=6&num_of_draws=1&num_of_boards=1&sum=15.00&msisdn=0';31let txn_id = 10000000;32let rawData = '';33const parseString = require('xml2js').parseString;34const https = require('https');35const urlLegacy = require('url'); // Legacy url module.36//const { URL } = require('url'); // ES6 url module37const fs = require('fs');38// The querystring module provides utilities for parsing and formatting URL query strings.39//const qs = require('querystring'); // used as let objBody = qs.parse(body, "\r\n", "=");40//const formidable = require('formidable');41//const {userInfo} = require('./appWeb.js');42let dtVar = new Date();43console.log('Server starts ' + dtVar.getSeconds() + "." + dtVar.getMilliseconds());44/*45//var envObj = process.env;46for (let prop in process.env) {47  //console.log(prop + ": " + process.env[prop]);48}49dtVar = new Date();50console.log('==================================== ' + dtVar.getSeconds() + "." + dtVar.getMilliseconds());51*/52// https://localhost:808153//const hostname = 'localhost';54// https://unl.test:808155const hostname = 'unl.test';56//const port = process.env.PORT; //  Windows - default port is 1337 for WebApp and 1542 for ConsoleApp;57const port = 8081; // for Linux must be set manually;58dtVar = new Date();59console.log('Before https.createServer() ' + dtVar.getSeconds() + "." + dtVar.getMilliseconds());60///*61let optSsl;62if (typeProj === 'build') {63  optSsl = {64    pfx: fs.readFileSync('../unl.test.pfx'), // '../../unl_works.pfx'65    passphrase: 'unl'66  };67}68else {69  optSsl = {70    pfx: fs.readFileSync('./unl.test.pfx'), // '../../unl_works.pfx'71    passphrase: 'unl'72  };73}74let options = optSsl;75//*/76//const server = http.createServer((req, res) => { // request is <http.IncomingMessage>, response is <http.ServerResponse> ...}77const server = https.createServer(options);78//const server = http.createServer();79server.on('error', (err) => {80  var dtVar = new Date();81  //throw err;82  console.log(`httpsServer 'error' event - error code: ==> ` + dtVar.getSeconds() + "." + dtVar.getMilliseconds());83  console.log(err.code);84  console.log('httpsServer error stack:');85  console.log(err.stack);86});87/*88server.on('connection', (socket) => {89  var dtVar = new Date();90  console.log(`httpsServer 'connection' event - client connected at + ==> ` + dtVar.getSeconds() + "." + dtVar.getMilliseconds());91  console.log(socket.remoteAddress + ' ' + socket.remoteFamily + ' ' + socket.remotePort);92});93*/94server.on('request', (req, res) => { // request is <http.IncomingMessage>, response is <http.ServerResponse>95  req.on('error', (err) => {96    // This prints the error message and stack trace to `stderr`.97    console.log(`httpsServer request 'error' event - error stack: ==> ` + dtVar.getSeconds() + "." + dtVar.getMilliseconds());98    console.error(err.stack);99  });100  res.on('error', (err) => {101    console.log(`httpsServer response 'error' event - error code: ==> ` + dtVar.getSeconds() + "." + dtVar.getMilliseconds());102    console.error(err);103  });104  // The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays,105  // or properties from objects, into distinct variables.106  //const { method, url, headers } = req;107  //let aaa = new Object();108  // req.url if GET "/" for very initial and for next  e.g. "styles/style.css" or "/submitFormAK?fname=Alex&sname=Raven"109  // if POST then e.g. "/submitformAK"110  let objUrl = urlLegacy.parse(req.url, true, true); // non standard object.111  //console.log(objUrl.pathname); // "/formAKpay"112  //console.log(objUrl.search); // "?q=ticreq"113  // Verify that it is very first page request or rendering page after GET or POST form submit processed.114  // After POST form submit will be processed rendering page will be as GET.115  // In req.headers Object property host: "unl.test:8081"116  // <==================== Begin of GET method form submit case ====================================================>117  if ((req.method === "GET")) {118    // for req.method === "GET" objUrl.search is ? + query e.g. "?q=123-12345678-1234567" or Null119    // req.url = "/" or e.g. "styles/style.css" or "/formAK?q=123-12345678-1234567"120    // if req.method === "POST" then ObjUrl.search will be "" always.121    /*122    req.url = "/" or e.g. "/submitformAK?fname=al&sname=kaa"123    ObjUrl {124      href: = path: "/ or e.g. "/submitformAK?fname=al&sname=kaa"125      pathname: "/" or e.g. "/submitformAK"126      search: null or  "?fname=al&sname=kaa"127      query: Object {} or {fname: "al", sname: "kaa"}128    }129    */130    if (objUrl.search === null) { // very initial request https://unl.test:8081/131      let contType = '';132      if (objUrl.pathname.endsWith('.css')) {133        contType = 'text/css';134      }135      else if (objUrl.pathname.endsWith('.js')) {136        contType = 'application/javascript';137      }138      else if (objUrl.pathname.endsWith('.json')) {139        contType = 'application/json';140      }141      else if (objUrl.pathname.endsWith('.map')) {142        contType = 'application/map';143      }144      else if (objUrl.pathname.endsWith('.ico')) {145        contType = 'image/bmp';146      }147      else if (objUrl.pathname.endsWith('.png')) {148        contType = 'image/png';149      }150      else if (objUrl.pathname.endsWith('.jpg') || objUrl.pathname.endsWith('.jpeg')) {151        contType = 'image/jpeg';152      }153      else if (objUrl.pathname.endsWith('.htm') || objUrl.pathname.endsWith('.html')) {154        contType = 'text/html';155      }156      else if (objUrl.pathname !== '/') {157        contType = 'application/octet-stream';158      }159      console.log('contType: [' + contType + '] <==============================');160      console.log('objUrl.pathname: ' + objUrl.pathname);161      //console.log('objUrl.path: ' + objUrl.path);162      if (contType === '') {  // default formNameIni e.g. indexForm.html.163        contType = 'text/html';164        console.log('Empty contType read file: ./' + dirName + '/' + formNameIni);165        fs.readFile('./' + dirName + '/' + formNameIni, (err, data) => {166          if (err) {167            res.writeHead(200, { 'Content-Type': `${contType}` });168            res.write(`Empty contType as ${dirName}/${formNameIni} not found!`);169            return res.end();170              } // throw err;171          else {172            res.writeHead(200, { 'Content-Type': 'text/html' });173            res.write(data);174            return res.end();175          }176        });177      }178      else {179        console.log('Non empty contType read file: ./' + dirName + objUrl.pathname);180        fs.readFile('./' + dirName + objUrl.pathname, (err, data) => { // './' + dirName  + "/path/name.type"181        if (err) {182          res.writeHead(200, { 'Content-Type': 'text/plain' });183          res.write(`Non empty contType ${contType} as ${dirName + objUrl.pathname} not found!`);184          return res.end();185            } // throw err;186        else {187            res.writeHead(200, { 'Content-Type': `${contType}` });188            res.write(data);189            return res.end();190          }191        });192      }193    } // end of objUrl.search === null -> no ? in GET request.194    else { // objUrl.search !== null, there is ? in GET request.195      // for req.method === "GET" objUrl.search is ? + query e.g. "?q=123-12345678-1234567" or Null if no ? in GET request.196      // req.url = "/formAK?q=123-12345678-1234567"197      /*198      req.url = "/formAK?q=123-12345678-1234567"199      ObjUrl {200      href: = path: /formNameIni?fname=al&sname=kaa"201      pathname: /formNameIni"202      search: "?fname=al&sname=kaa"203      query: {fname: "al", sname: "kaa"}204      }205      */206      // HACKER ATTACK OR FAULTY CLIENT.207      //req.connection.destroy();208      //req.url = "/formAKval?q=123-12345678-1234567"209      //console.log(objUrl.pathname); // "/formAKval"210      //console.log(objUrl.search); // "?q=123-12345678-1234567"211      if (req.url.indexOf('/formAKchk?') >= 0) {212        /*213        res.writeHead(200, { 'Content-Type': 'text/xml' });214        //res.write('');215        res.write('<?xml version="1.0" encoding="UTF-8"?>');216        res.write('<response>');217        res.write('<ticket>225-13818091-1101234</ticket>');218        res.write('<game>2</game>');219        res.write('<sum>10.00</sum>');220        res.write(`<result>0</result>`);221        res.write('</response>');222        */223        /*224        ElseIf (InStrRev(strBuf, "PPAY", -1, CompareMethod.Text) > 0) Then225        ReqStruct.sum = -1226        ElseIf (InStrRev(strBuf, "CASH", -1, CompareMethod.Text) > 0) Then227        ReqStruct.sum = -2228        ElseIf (InStrRev(strBuf, "CSHX", -1, CompareMethod.Text) > 0) Then229        ReqStruct.sum = -3230        ElseIf (InStrRev(strBuf, "VCAN", -1, CompareMethod.Text) > 0) Then231        ReqStruct.sum = -4232        ElseIf (InStrRev(strBuf, "VDEL", -1, CompareMethod.Text) > 0) Then233        ReqStruct.sum = 0234        */235        //ValTicket('225-13818091-1101234', res);236        let ticnum = '';237        //objUrl.search is e.g. "?q=123-12345678-1234567"238        ticnum = objUrl.search.slice(objUrl.search.indexOf('=') + 1);239        rawData = '';240        CheckValTicket(ticnum, res);241        //console.log(`rawData in server.on('request', (req, res) ...) event :`)242        //console.log(rawData); // will be empy ''.243        //res.write(rawData);244      } // end of if (req.url.indexOf('/formAK?') >= 0)245      //req.url = "/formAKpay?q=ticreq"246      //console.log(objUrl.pathname); // "/formAKpay"247      //console.log(objUrl.search); // "?q=ticreq"248      else if (req.url.indexOf('/formAKpay?') >= 0) {249        let ticreq = '';250        //objUrl.search is e.g. "?q=123-12345678-1234567"251        ticreq = objUrl.search.slice(objUrl.search.indexOf('=') + 1);252        rawData = '';253        BuyTicket(ticreq, res);254      }255      else {256        //res.writeHead(200, { 'Content-Type': 'text/plain' });257        //res.write(`Form request submitted by GET. Action URL with search: ${req.url}`);258        res.writeHead(200, { 'Content-Type': 'text/html' });259        res.write('<!DOCTYPE html>');260        res.write('<html lang="en">');261        res.write('<head>');262        res.write('<meta charset="utf-8" />');263        res.write('<meta name="viewport" content="width=device-width, initial-scale=1.0" />');264        res.write('<title>Unknown Form request submitted by GET</title>');265        res.write('<style>');266        res.write('#ticinfo {');267        //res.write('width: 70%;');268        res.write('margin: 3% 3% 3% 3%;');269        res.write('background-color: #dfdbdb;');270        res.write('border: thick solid black;');271        res.write('outline: dashed red;');272        res.write('}');273        res.write('#ticback {');274        res.write('display: block;')275        res.write('width: 10%;');276        res.write('margin: 3% 3% 3% 3%;');277        res.write('padding: 1% 1% 1% 1%;');278        res.write('color: white;')279        res.write('background-color: blue;');280        res.write('border: thin solid black;');281        res.write('border-radius: 15%;')282        res.write('text-decoration:none;')283        res.write('}');284        res.write('#ticket {');285        res.write('display: block;')286        res.write('margin: 3% 3% 3% 3%;');287        res.write('padding: 1% 1% 1% 1%;');288        res.write('background-color: white;');289        res.write('border: thin solid black;');290        res.write('}');291        res.write('</style>');292        res.write('</head>');293        res.write('<body>');294        res.write('<div id="ticinfo">');295        res.write('<a id="ticback" href="/">Back</a>');296        res.write('<h4>Unknown Form request submitted by GET</h4>');297        res.write(`GET action URL (form name with search included): ${req.url}`);298        res.write('</p>');299        res.write('</div>');300        res.write('</body>');301        res.write('</html>');302        res.end();303        return res.end();304      }305      //return res.end();306    }307  } // <==================== End of GET method form submit case ====================================================>308  else { // <==================== Begin of POST method form submit case ============================================>309    // POST method. NB! If req.method === "POST" then ObjUrl.search will be Null always.310    //let objUrl = urlLegacy.parse(req.url, true, true); // non standard object is got earlier befor GET or POST analyze.311    /*312    req.url = "/formNameIni"313    ObjUrl {314      href: = path: = pathname:  "/formNameIni"315      search: null316      query: Object {}317    }318    later body will be319    body: "fname=al\r\nsname=kaa\r\n"320    */321    let body = '';322    req.on('data', function (data) {323      body += data;324      // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB.325      if (body.length > 1e6) {326        // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST.327        req.connection.destroy();328      }329    });330    req.on('end', function () {331      // e.g. body = 'fname=Alex\r\nsname=Raven\r\n' for /formNameIni332      /*333      console.log(body);334      let strVar = '';335      for (let i = 0; i < body.length; i++) {336        strVar = strVar + body.charCodeAt(i) + ",";337      }338      console.log(strVar);339      */340      //console.log(objBody);341      //let objBody = qs.parse(body, "\r\n", "="); // using const qs = require('querystring') module.342      /*343        req.url = "/submitformAK"344        ObjUrl {345          href: = path: = pathname:  "/submitformAK"346          search: null347          query: Object {}348        }349        body: "fname=al\r\nsname=kaa\r\n"350        objBody: Object {fname: "al", sname: "kaa"}    }351      */352      // HACKER ATTACK OR FAULTY CLIENT.353      //req.connection.destroy();354      //res.writeHead(200, { 'Content-Type': 'text/plain' });355      //res.write(`Form request submitted by POST. Action URL is ${req.url} with search as body: \r\n${body}`);356      res.writeHead(200, { 'Content-Type': 'text/html' });357      res.write('<!DOCTYPE html>');358      res.write('<html lang="en">');359      res.write('<head>');360      res.write('<meta charset="utf-8" />');361      res.write('<meta name="viewport" content="width=device-width, initial-scale=1.0" />');362      res.write('<title>Form request submitted by POST</title>');363      res.write('<style>');364      res.write('#ticinfo {');365      //res.write('width: 70%;');366      res.write('margin: 3% 3% 3% 3%;');367      res.write('background-color: #dfdbdb;');368      res.write('border: thick solid black;');369      res.write('outline: dashed red;');370      res.write('}');371      res.write('#ticback {');372      res.write('display: block;')373      res.write('width: 10%;');374      res.write('margin: 3% 3% 3% 3%;');375      res.write('padding: 1% 1% 1% 1%;');376      res.write('color: white;')377      res.write('background-color: blue;');378      res.write('border: thin solid black;');379      res.write('border-radius: 15%;')380      res.write('text-decoration:none;')381      res.write('}');382      res.write('#ticket {');383      res.write('display: block;')384      res.write('margin: 3% 3% 3% 3%;');385      res.write('padding: 1% 1% 1% 1%;');386      res.write('background-color: white;');387      res.write('border: thin solid black;');388      res.write('}');389      res.write('</style>');390      res.write('</head>');391      res.write('<body>');392      res.write('<div id="ticinfo">');393      res.write('<a id="ticback" href="/">Back</a>');394      res.write('<h4>Form request submitted by POST</h4>');395      res.write('<p id="ticket">');396      res.write(`POST action (form name) as URL is ${req.url} with search as body: ${body}`);397      res.write('</p>');398      res.write('</div>');399      res.write('</body>');400      res.write('</html>');401      res.end();402      return res.end();403    }); // end req.on('end', function ()...404  } // <==================================== End of POST method form submit case ===================================>405}) // end of server.on('request'...)406dtVar = new Date();407console.log('After https.createServer ' + dtVar.getSeconds() + "." + dtVar.getMilliseconds());408// Begin accepting connections on the specified port and hostname.409// If hostname is omitted, server will accept connections on the unspecified IPv6 address (::) when IPv6 is available,410// or the unspecified IPv4 address (0.0.0.0) otherwise.411server.listen(port, hostname, () => {412  // Place holders in template literals are indicated by the $ (Dollar sign) and curly braces e.g. (${expression}).413  console.log(`Server running and listening at https://${hostname}:${port}/ ` + dtVar.getSeconds() + "." + dtVar.getMilliseconds()); // ${expression} is place holders in template literal enclosed by the back-tick (` `) (grave accent) characters.414});415dtVar = new Date();416console.log('End Serer main PROGAM path after server.listen(port, hostname, callback) ' + dtVar.getSeconds() + "." + dtVar.getMilliseconds());417// <==================================== ValTicket =====================================>418function CheckValTicket(ticnum, res2) {419  // reqString e.g. "http://10.8.194.3:9994/?agent=58&type=2&command=checkval&ticket_number="420  console.log(reqString + ticnum);421  http.get(reqString + ticnum, (res) => {422    const { statusCode } = res;423    const contentType = res.headers['content-type'];424    let error;425    if (statusCode !== 200) {426      error = new Error(`Request Failed.\n Status Code: ${statusCode}`);427    }428    else if (!/^text\/xml/.test(contentType)) {429      error = new Error(`Invalid content-type.\n Expected text/xml but received ${contentType}`);430    }431    if (error) {432      console.error(error.message);433      // consume response data to free up memory434      res.resume();435      //return error.message;436    }437    res.setEncoding('utf8');438    //let rawData = '';439    res.on('data', (chunk) => { rawData += chunk; });440    res.on('end', () => {441      try {442        //const parsedData = JSON.parse(rawData);443        //console.log(parsedData);444        console.log(`rawData in client http.on('end', ...) event :`)445        console.log(rawData);446        let reply;447        reply = '';448        let errmsg = '';449        parseString(rawData, function (err, result) {450            if (err !== null) {451              //console.log(err.message);452              // "Non-whitespace before first tag.\nLine: 0\nColumn: 1\nChar: ?"453              errmsg = err.message.replace('\n',' ');454              while (errmsg.indexOf('\n') !== -1) {455                errmsg = errmsg.replace('\n',' ');456              }457              //console.log(errmsg);458            }459            else {460              //console.log(result);461              reply = result;462            }463        });464        let sum = '';465        let ticinfo = '';466        if (reply !== '') {467          //console.log('reply:');468          //console.log(reply.response.result[0]);469          if (reply.response.result[0] === '0') {470            sum = reply.response.sum[0];471            //console.log('sum =' + sum);472            if (sum === '-1.00') {473              ticinfo = `ÐолÑÑой вÑигÑÑÑ!!!.`474            }475            else if (sum === '-2.00') {476              ticinfo = `ÐÐ¸Ð»ÐµÑ Ñже вÑплаÑен.`477            }478            else if (sum === '-3.00') {479              ticinfo = `ÐÐ¸Ð»ÐµÑ Ð²ÑплаÑен Ñ Ð¾Ð±Ð¼ÐµÐ½Ð½Ñм билеÑом.`480            }481            else if (sum === '-4.00') {482              ticinfo = `ÐÐ¸Ð»ÐµÑ Ð°Ð½Ð½ÑлиÑован.`483            }484            else if (sum === '0.00') {485              ticinfo = `ÐÐ¸Ð»ÐµÑ Ð½Ðµ вÑигÑал.`486            }487            else {488              ticinfo = `ÐÐ°Ñ Ð²Ð¸Ð³ÑÐ°Ñ ${sum} гÑн.`489            }490            console.log(ticinfo);491          }492          else {493            ticinfo = 'Server reply with result: ' + reply.response.result[0];494            console.log(ticinfo);495          }496        }497        else {498          ticinfo = 'XML wrong format:' + errmsg;499        }500        //res2.writeHead(200, { 'Content-Type': 'text/xml' });501        //res2.write(rawData);502        // Content-Type: text/xml; charset=UTF-8503        //res2.writeHead(200, { 'Content-Type': 'text/plain; charset=UTF-8' });504        //res2.write('Ticket info: ' + ticinfo);505        res2.writeHead(200, { 'Content-Type': 'text/html' });506        res2.write('<!DOCTYPE html>');507        res2.write('<html lang="en">');508        res2.write('<head>');509        res2.write('<meta charset="utf-8" />');510        res2.write('<meta name="viewport" content="width=device-width, initial-scale=1.0" />');511        res2.write('<title>Ticket info</title>');512        res2.write('<style>');513        res2.write('#ticinfo {');514        //res2.write('width: 70%;');515        res2.write('margin: 3% 3% 3% 3%;');516        res2.write('background-color: #dfdbdb;');517        res2.write('border: thick solid black;');518        res2.write('outline: dashed red;');519        res2.write('}');520        res2.write('#ticback {');521        res2.write('display: block;')522        res2.write('width: 10%;');523        res2.write('margin: 3% 3% 3% 3%;');524        res2.write('padding: 1% 1% 1% 1%;');525        res2.write('color: white;')526        res2.write('background-color: blue;');527        res2.write('border: thin solid black;');528        res2.write('border-radius: 15%;')529        res2.write('text-decoration:none;')530        res2.write('}');531        res2.write('#ticket {');532        res2.write('display: block;')533        res2.write('margin: 3% 3% 3% 3%;');534        res2.write('padding: 1% 1% 1% 1%;');535        res2.write('background-color: white;');536        res2.write('border: thin solid black;');537        res2.write('}');538        //res2.write('');539        res2.write('</style>');540        res2.write('</head>');541        res2.write('<body>');542        res2.write('<div id="ticinfo">');543        res2.write('<a id="ticback" href="/">Back</a>');544        res2.write('<p id="ticket">');545        res2.write(ticinfo);546        res2.write('</p>');547        res2.write('</div>');548        res2.write('</body>');549        res2.write('</html>');550        //res2.write('');551      } catch (e) {552        console.error(e.message);553        res2.writeHead(200, { 'Content-Type': 'text/html' });554        res2.write('<!DOCTYPE html>');555        res2.write('<html lang="en">');556        res2.write('<head>');557        res2.write('<meta charset="utf-8" />');558        res2.write('<meta name="viewport" content="width=device-width, initial-scale=1.0" />');559        res2.write('<title>Ticket info processing error</title>');560        res2.write('<style>');561        res2.write('#ticinfo {');562        //res2.write('width: 70%;');563        res2.write('margin: 3% 3% 3% 3%;');564        res2.write('background-color: #dfdbdb;');565        res2.write('border: thick solid black;');566        res2.write('outline: dashed red;');567        res2.write('}');568        res2.write('#ticback {');569        res2.write('display: block;')570        res2.write('width: 10%;');571        res2.write('margin: 3% 3% 3% 3%;');572        res2.write('padding: 1% 1% 1% 1%;');573        res2.write('color: white;')574        res2.write('background-color: blue;');575        res2.write('border: thin solid black;');576        res2.write('border-radius: 15%;')577        res2.write('text-decoration:none;')578        res2.write('}');579        res2.write('#ticket {');580        res2.write('display: block;')581        res2.write('margin: 3% 3% 3% 3%;');582        res2.write('padding: 1% 1% 1% 1%;');583        res2.write('background-color: white;');584        res2.write('border: thin solid black;');585        res2.write('}');586        //res2.write('');587        res2.write('</style>');588        res2.write('</head>');589        res2.write('<body>');590        res2.write('<div id="ticinfo">');591        res2.write('<a id="ticback" href="/">Back</a>');592        res2.write('<h4>Ticket info processing error</h4>');593        res2.write('<p id="ticket">');594        res2.write(e.message);595        res2.write('</p>');596        res2.write('</div>');597        res2.write('</body>');598        res2.write('</html>');599      }600      res2.end();601      //return rawData;602    });603  }).on('error', (e) => {604    // e.message e.g. "connect ETIMEDOUT 10.8.194.3:9993"605    console.error(`Got error: ${e.message}`);606    res2.writeHead(200, { 'Content-Type': 'text/html' });607    res2.write('<!DOCTYPE html>');608    res2.write('<html lang="en">');609    res2.write('<head>');610    res2.write('<meta charset="utf-8" />');611    res2.write('<meta name="viewport" content="width=device-width, initial-scale=1.0" />');612    res2.write('<title>Ticket info network error</title>');613    res2.write('<style>');614    res2.write('#ticinfo {');615    //res2.write('width: 70%;');616    res2.write('margin: 3% 3% 3% 3%;');617    res2.write('background-color: #dfdbdb;');618    res2.write('border: thick solid black;');619    res2.write('outline: dashed red;');620    res2.write('}');621    res2.write('#ticback {');622    res2.write('display: block;')623    res2.write('width: 10%;');624    res2.write('margin: 3% 3% 3% 3%;');625    res2.write('padding: 1% 1% 1% 1%;');626    res2.write('color: white;')627    res2.write('background-color: blue;');628    res2.write('border: thin solid black;');629    res2.write('border-radius: 15%;')630    res2.write('text-decoration:none;')631    res2.write('}');632    res2.write('#ticket {');633    res2.write('display: block;')634    res2.write('margin: 3% 3% 3% 3%;');635    res2.write('padding: 1% 1% 1% 1%;');636    res2.write('background-color: white;');637    res2.write('border: thin solid black;');638    res2.write('}');639    //res2.write('');640    res2.write('</style>');641    res2.write('</head>');642    res2.write('<body>');643    res2.write('<div id="ticinfo">');644    res2.write('<a id="ticback" href="/">Back</a>');645    res2.write('<h4>Ticket info network error</h4>');646    res2.write('<p id="ticket">');647    res2.write(e.message);648    res2.write('</p>');649    res2.write('</div>');650    res2.write('</body>');651    res2.write('</html>');652    res2.end();653    //return e.message;654  });655} // end of function ValTicket(ticnum, res2)656// <==================================== ValTicket =====================================>657function BuyTicket(ticreq, res2) {658  console.log(reqStringPay + ticreq);659  reqStringPay = urlpay + '?agent=65&type=2&command=pay&date=20200808&txn_id=' + txn_id + '&game=6&num_of_draws=1&num_of_boards=1&sum=15.00&msisdn=0';660  txn_id = txn_id + 1;661  http.get(reqStringPay, (res) => { // reqStringPay + ticreq for manual non-auto.662    const { statusCode } = res;663    const contentType = res.headers['content-type'];664    let error;665    if (statusCode !== 200) {666      error = new Error(`Request Failed.\n Status Code: ${statusCode}`);667    }668    else if (!/^text\/xml/.test(contentType)) {669      error = new Error(`Invalid content-type.\n Expected text/xml but received ${contentType}`);670    }671    if (error) {672      console.error(error.message);673      // consume response data to free up memory674      res.resume();675      //return error.message;676    }677    res.setEncoding('utf8');678    //let rawData = '';679    res.on('data', (chunk) => { rawData += chunk; });680    res.on('end', () => {681      try {682        let dtVar = new Date();683        //const parsedData = JSON.parse(rawData);684        //console.log(parsedData);685        console.log(`rawData in client http.on('end', ...) event :`)686        console.log(rawData);687        let reply;688        reply = '';689        let errmsg = '';690        parseString(rawData, function (err, result) {691            if (err !== null) {692              //console.log(err.message);693              // "Non-whitespace before first tag.\nLine: 0\nColumn: 1\nChar: ?"694              errmsg = err.message.replace('\n',' ');695              while (errmsg.indexOf('\n') !== -1) {696                errmsg = errmsg.replace('\n',' ');697              }698              //console.log(errmsg);699            }700            else {701              //console.log(result);702              reply = result;703            }704        });705        //let sum = '';706        let ticinfo = '';707        let decrInfo = '';708        if (reply !== '') {709          //console.log('reply:');710          //console.log(reply.response.result[0]);711          if (reply.response.result[0] === '0') {712            //sum = reply.response.sum[0];713            //console.log('sum =' + sum);714            ticinfo = ticinfo + '<li>УкÑаÑнÑÑка ÐаÑÑоналÑна ÐоÑеÑеÑ</li>';715            ticinfo = ticinfo + '<li>ÐаÑа: ' + reply.response.ticket[0].date[0] + '</li>';716            ticinfo = ticinfo + '<li>ЧаÑ: '  + reply.response.ticket[0].time[0] + '</li>';717            ticinfo = ticinfo + '<li>ÐомбÑнаÑиÑ: '  + reply.response.ticket[0].board1a[0] + '</li>'718            ticinfo = ticinfo + '<li>СÑма: '  + reply.response.ticket[0].sum[0] + '</li>';719            decrInfo = decrEx(reply.response.ticket[0].gguard[0], reply.response.ticket[0].number[0]);720            //console.log(decrInfo);721            ticinfo = ticinfo + '<li>ÐÑлеÑ: '  + decrInfo + '</li>'722            //ticinfo = ticinfo + '<li>ÐÐ¾Ð¼ÐµÑ Ð±ÑлеÑа: '  + reply.response.ticket[0].number[0] + '</li>';723            //ticinfo = ticinfo + '<li>Ðод: '  + reply.response.ticket[0].gguard[0] + '</li>';724            ticinfo = ticinfo + '<li>txn_id: '  + reply.response.txn_id[0] + '</li>';725            console.log(ticinfo);726          }727          else {728            ticinfo = 'Server reply with result: ' + reply.response.result[0];729            console.log(ticinfo);730          }731        }732        else {733          ticinfo = 'XML wrong format:' + errmsg;734        }735        //res2.writeHead(200, { 'Content-Type': 'text/xml' });736        //res2.write(rawData);737        // Content-Type: text/xml; charset=UTF-8738        //res2.writeHead(200, { 'Content-Type': 'text/plain; charset=UTF-8' });739        //res2.write('Ticket info: ' + ticinfo);740        res2.writeHead(200, { 'Content-Type': 'text/html' });741        res2.write('<!DOCTYPE html>');742        res2.write('<html lang="en">');743        res2.write('<head>');744        res2.write('<meta charset="utf-8" />');745        res2.write('<meta name="viewport" content="width=device-width, initial-scale=1.0" />');746        res2.write('<title>Ticket info</title>');747        res2.write('<style>');748        res2.write('#ticinfo {');749        //res2.write('width: 70%;');750        res2.write('margin: 3% 3% 3% 3%;');751        res2.write('background-color: #dfdbdb;');752        res2.write('border: thick solid black;');753        res2.write('outline: dashed red;');754        res2.write('}');755        res2.write('#ticback {');756        res2.write('display: block;')757        res2.write('width: 10%;');758        res2.write('margin: 1% 3% 1% 3%;');759        res2.write('padding: 1% 1% 1% 1%;');760        res2.write('color: white;')761        res2.write('background-color: blue;');762        res2.write('border: thin solid black;');763        res2.write('border-radius: 15%;')764        res2.write('text-decoration:none;')765        res2.write('}');766        res2.write('#tichdr {');767        res2.write('margin: 1% 3% 1% 3%;');768        //res2.write('padding: 1% 1% 1% 1%;');769        res2.write('}');770        res2.write('#ticket {');771        res2.write('display: block;')772        res2.write('margin: 1% 3% 1% 3%;');773        res2.write('padding: 1% 1% 1% 1%;');774        res2.write('background-color: white;');775        res2.write('border: thin solid black;');776        res2.write('}');777        //res2.write('');778        res2.write('</style>');779        res2.write('</head>');780        res2.write('<body>');781        res2.write('<div id="ticinfo">');782        res2.write('<a id="ticback" href="/">Back</a>');783        res2.write('<h3 id="tichdr">ÐÐ°Ñ Ð±Ð¸Ð»ÐµÑ Ð·Ð°ÑегиÑÑÑиÑован: ' + dtVar.toLocaleString() + '</h3>');784        res2.write('<ul id="ticket">');785        res2.write(ticinfo);786        res2.write('</ul>');787        res2.write('</div>');788        res2.write('</body>');789        res2.write('</html>');790        //res2.write('');791      } catch (e) {792        console.error(e.message);793        res2.writeHead(200, { 'Content-Type': 'text/html' });794        res2.write('<!DOCTYPE html>');795        res2.write('<html lang="en">');796        res2.write('<head>');797        res2.write('<meta charset="utf-8" />');798        res2.write('<meta name="viewport" content="width=device-width, initial-scale=1.0" />');799        res2.write('<title>Ticket info processing error</title>');800        res2.write('<style>');801        res2.write('#ticinfo {');802        //res2.write('width: 70%;');803        res2.write('margin: 3% 3% 3% 3%;');804        res2.write('background-color: #dfdbdb;');805        res2.write('border: thick solid black;');806        res2.write('outline: dashed red;');807        res2.write('}');808        res2.write('#ticback {');809        res2.write('display: block;')810        res2.write('width: 10%;');811        res2.write('margin: 3% 3% 3% 3%;');812        res2.write('padding: 1% 1% 1% 1%;');813        res2.write('color: white;')814        res2.write('background-color: blue;');815        res2.write('border: thin solid black;');816        res2.write('border-radius: 15%;')817        res2.write('text-decoration:none;')818        res2.write('}');819        res2.write('#ticket {');820        res2.write('display: block;')821        res2.write('margin: 3% 3% 3% 3%;');822        res2.write('padding: 1% 1% 1% 1%;');823        res2.write('background-color: white;');824        res2.write('border: thin solid black;');825        res2.write('}');826        //res2.write('');827        res2.write('</style>');828        res2.write('</head>');829        res2.write('<body>');830        res2.write('<div id="ticinfo">');831        res2.write('<a id="ticback" href="/">Back</a>');832        res2.write('<h4>Ticket info processing error</h4>');833        res2.write('<p id="ticket">');834        res2.write(e.message);835        res2.write('</p>');836        res2.write('</div>');837        res2.write('</body>');838        res2.write('</html>');839      }840      res2.end();841      //return rawData;842    });843  }).on('error', (e) => {844    // e.message e.g. "connect ETIMEDOUT 10.8.194.3:9993"845    console.error(`Got error: ${e.message}`);846    res2.writeHead(200, { 'Content-Type': 'text/html' });847    res2.write('<!DOCTYPE html>');848    res2.write('<html lang="en">');849    res2.write('<head>');850    res2.write('<meta charset="utf-8" />');851    res2.write('<meta name="viewport" content="width=device-width, initial-scale=1.0" />');852    res2.write('<title>Ticket info network error</title>');853    res2.write('<style>');854    res2.write('#ticinfo {');855    //res2.write('width: 70%;');856    res2.write('margin: 3% 3% 3% 3%;');857    res2.write('background-color: #dfdbdb;');858    res2.write('border: thick solid black;');859    res2.write('outline: dashed red;');860    res2.write('}');861    res2.write('#ticback {');862    res2.write('display: block;')863    res2.write('width: 10%;');864    res2.write('margin: 3% 3% 3% 3%;');865    res2.write('padding: 1% 1% 1% 1%;');866    res2.write('color: white;')867    res2.write('background-color: blue;');868    res2.write('border: thin solid black;');869    res2.write('border-radius: 15%;')870    res2.write('text-decoration:none;')871    res2.write('}');872    res2.write('#ticket {');873    res2.write('display: block;')874    res2.write('margin: 3% 3% 3% 3%;');875    res2.write('padding: 1% 1% 1% 1%;');876    res2.write('background-color: white;');877    res2.write('border: thin solid black;');878    res2.write('}');879    //res2.write('');880    res2.write('</style>');881    res2.write('</head>');882    res2.write('<body>');883    res2.write('<div id="ticinfo">');884    res2.write('<a id="ticback" href="/">Back</a>');885    res2.write('<h4>Ticket info network error</h4>');886    res2.write('<p id="ticket">');887    res2.write(e.message);888    res2.write('</p>');889    res2.write('</div>');890    res2.write('</body>');891    res2.write('</html>');892    res2.end();893    //return e.message;894  });895} // end of function BuyTicket(ticnum, res2)896function decrEx(strGGuardEnc, strTicEnc) {897  var strOut;898  var strGguardIn, strNumberIn; // var strJulian;899  var strReturn, strGGuard, strTicNum, strCheckDigits;900  var strArr; // intVar, i;901  var strGGuardArr, strJulianArr, strTicNumArr, strCheckDigitsArr;902  //console.log(`input: ${strGGuardEnc} ${strInEnc}`);903  strOut="";904  if (typeof(strGGuardEnc) != "string") return "ERROR2";905  if (typeof(strTicEnc) != "string") return "ERROR3";906  // e.g. strGGuardEnc="123456" and strTicEnc = "123-12345678-1234567"907  strGguardIn = String(strGGuardEnc);908  strNumberIn = String(strTicEnc);909  if (strGguardIn.length != 6)  return "ERROR2";910  if (strNumberIn.length != 20) return "ERROR3";911  //intVar = Number(strGguardIn);912  //console.log(intVar + " " + typeof(intVar));913  if (! Number.isInteger(Number(strGguardIn))) return "ERROR2"; 914  strArr = strNumberIn.split("-");915  if (strArr.length != 3) return "ERROR3";916  if (strArr[0].length != 3) return "ERROR3";917  if (strArr[1].length != 8) return "ERROR3";918  if (strArr[2].length != 7) return "ERROR3";919  if (! Number.isInteger(Number(strArr[0]))) return "ERROR3"; 920  if (! Number.isInteger(Number(strArr[1]))) return "ERROR3"; 921  if (! Number.isInteger(Number(strArr[2]))) return "ERROR3"; 922  //var strGGuardArr, strJulianArr, strTicNumArr, strChcekDigitsArr;923  strGGuardArr = strGguardIn.split("");924  strJulianArr = strArr[0].split("");925  strTicNumArr = strArr[1].split("");926  strCheckDigitsArr = strArr[2].split("");927  strGGuard = addon.unld(strGGuardArr[0], strGGuardArr[1], strGGuardArr[2], strGGuardArr[3], strGGuardArr[4], strGGuardArr[5], "G", "G", strJulianArr[0], strJulianArr[1], strJulianArr[2]); // gGuard.928  //console.log('Return string:', strGGuard + " typeof: " + typeof(strGGuard)); // gguard.929  strTicNum = addon.unld(strTicNumArr[0], strTicNumArr[1], strTicNumArr[2], strTicNumArr[3], strTicNumArr[4], strTicNumArr[5], strTicNumArr[6], strTicNumArr[7], strJulianArr[0], strJulianArr[1], strJulianArr[2]); // external number.930  //console.log('Return string:', strTicNum + " typeof: " + typeof(strTicNum)); // TicNum external number.931  strCheckDigits = addon.unld(strCheckDigitsArr[0], strCheckDigitsArr[1], strCheckDigitsArr[2], strCheckDigitsArr[3], strCheckDigitsArr[4], strCheckDigitsArr[5], strCheckDigitsArr[6], "D", strJulianArr[0], strJulianArr[1], strJulianArr[2]); // check Digits.932  //console.log('Return string:', strCheckDigits + " typeof: " + typeof(strCheckDigits)); // gguard, num, check.933  strOut = strGGuard + " " + strArr[0] + "-" + strTicNum + "-" + strCheckDigits;934  //console.log(`output: ${strOut}`);935  //strArr = strIn.split("-");936  //strOut = strArr[2] + "-" + strArr[1] + "-" + strArr[0];937  938  ExitFunction:939  return strOut;...nodeServerTestDiag.js
Source:nodeServerTestDiag.js  
1'use strict'; // is unnecessary inside of modules.2//file:///home/akaarna/react-tutorial/build/index.html3/*4Standard dirs should be:5images6pages7scripts8styles9*/10/*11Can be started as parent in build subdir:12  >node ..\nodeServerTestDiag.js13*/14let typeProj =  ''; // 'build';15let dirName = 'build'; // React build dir as root dir.16//let dirName = ''; // root dir.17//let methodType = 'get'; // 'post' or 'get' for secure server.18//let formNameIni = 'submitFormAK-Ini';19//let formName = 'submitFormAK';20//let dirName = 'arch'; // root dir.21let formNameIni = 'index.html';22//let formNameIni = 'indexForm.html';23//let formName = 'submitFormAK';24// Using special formName  /formAKchk?q=123-12345678-1234567 /formAKval?q=123-12345678-1234567 or /formAKpay?q=xxx25const http = require('http');26const urlval = 'http://10.8.194.3:9994/'; // project WinTicsCheckNoSslTEST new at 'http://10.8.194.3:9994/'27//let reqString = urlval + '?agent=58&type=2&command=checkval&ticket_number=225-13818091-1101234';28let reqString = urlval + '?agent=58&type=2&command=checkval&ticket_number='; // + search;29const urlpay = 'http://10.8.194.3:10064/'; // project UnlCashExTEST ver. 3.830let reqStringPay; //= urlpay + '?agent=65&type=2&command=pay&date=20200808&txn_id=' + txn_id + '&game=6&num_of_draws=1&num_of_boards=1&sum=15.00&msisdn=0';31let txn_id = 10000000;32let rawData = '';33const parseString = require('xml2js').parseString;34const https = require('https');35const urlLegacy = require('url'); // Legacy url module.36//const { URL } = require('url'); // ES6 url module37const fs = require('fs');38// The querystring module provides utilities for parsing and formatting URL query strings.39//const qs = require('querystring'); // used as let objBody = qs.parse(body, "\r\n", "=");40//const formidable = require('formidable');41//const {userInfo} = require('./appWeb.js');42let dtVar = new Date();43console.log('Server starts ' + dtVar.getSeconds() + "." + dtVar.getMilliseconds());44/*45//var envObj = process.env;46for (let prop in process.env) {47  //console.log(prop + ": " + process.env[prop]);48}49dtVar = new Date();50console.log('==================================== ' + dtVar.getSeconds() + "." + dtVar.getMilliseconds());51*/52// https://localhost:808153//const hostname = 'localhost';54// https://unl.test:808155const hostname = 'unl.test';56//const port = process.env.PORT; //  Windows - default port is 1337 for WebApp and 1542 for ConsoleApp;57const port = 8081; // for Linux must be set manually;58dtVar = new Date();59console.log('Before https.createServer() ' + dtVar.getSeconds() + "." + dtVar.getMilliseconds());60///*61let optSsl;62if (typeProj === 'build') {63  optSsl = {64    pfx: fs.readFileSync('../unl.test.pfx'), // '../../unl_works.pfx'65    passphrase: 'unl'66  };67}68else {69  optSsl = {70    pfx: fs.readFileSync('./unl.test.pfx'), // '../../unl_works.pfx'71    passphrase: 'unl'72  };73}74let options = optSsl;75//*/76//const server = http.createServer((req, res) => { // request is <http.IncomingMessage>, response is <http.ServerResponse> ...}77const server = https.createServer(options);78//const server = http.createServer();79server.on('error', (err) => {80  var dtVar = new Date();81  //throw err;82  console.log(`httpsServer 'error' event - error code: ==> ` + dtVar.getSeconds() + "." + dtVar.getMilliseconds());83  console.log(err.code);84  console.log('httpsServer error stack:');85  console.log(err.stack);86});87/*88server.on('connection', (socket) => {89  var dtVar = new Date();90  console.log(`httpsServer 'connection' event - client connected at + ==> ` + dtVar.getSeconds() + "." + dtVar.getMilliseconds());91  console.log(socket.remoteAddress + ' ' + socket.remoteFamily + ' ' + socket.remotePort);92});93*/94server.on('request', (req, res) => { // request is <http.IncomingMessage>, response is <http.ServerResponse>95  req.on('error', (err) => {96    // This prints the error message and stack trace to `stderr`.97    console.log(`httpsServer request 'error' event - error stack: ==> ` + dtVar.getSeconds() + "." + dtVar.getMilliseconds());98    console.error(err.stack);99  });100  res.on('error', (err) => {101    console.log(`httpsServer response 'error' event - error code: ==> ` + dtVar.getSeconds() + "." + dtVar.getMilliseconds());102    console.error(err);103  });104  // The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays,105  // or properties from objects, into distinct variables.106  //const { method, url, headers } = req;107  //let aaa = new Object();108  // req.url if GET "/" for very initial and for next  e.g. "styles/style.css" or "/submitFormAK?fname=Alex&sname=Raven"109  // if POST then e.g. "/submitformAK"110  let objUrl = urlLegacy.parse(req.url, true, true); // non standard object.111  //console.log(objUrl.pathname); // "/formAKpay"112  //console.log(objUrl.search); // "?q=ticreq"113  // Verify that it is very first page request or rendering page after GET or POST form submit processed.114  // After POST form submit will be processed rendering page will be as GET.115  // In req.headers Object property host: "unl.test:8081"116  // <==================== Begin of GET method form submit case ====================================================>117  if ((req.method === "GET")) {118    // for req.method === "GET" objUrl.search is ? + query e.g. "?q=123-12345678-1234567" or Null119    // req.url = "/" or e.g. "styles/style.css" or "/formAK?q=123-12345678-1234567"120    // if req.method === "POST" then ObjUrl.search will be "" always.121    /*122    req.url = "/" or e.g. "/submitformAK?fname=al&sname=kaa"123    ObjUrl {124      href: = path: "/ or e.g. "/submitformAK?fname=al&sname=kaa"125      pathname: "/" or e.g. "/submitformAK"126      search: null or  "?fname=al&sname=kaa"127      query: Object {} or {fname: "al", sname: "kaa"}128    }129    */130    if (objUrl.search === null) { // very initial request https://unl.test:8081/131      let contType = '';132      if (objUrl.pathname.endsWith('.css')) {133        contType = 'text/css';134      }135      else if (objUrl.pathname.endsWith('.js')) {136        contType = 'application/javascript';137      }138      else if (objUrl.pathname.endsWith('.json')) {139        contType = 'application/json';140      }141      else if (objUrl.pathname.endsWith('.map')) {142        contType = 'application/map';143      }144      else if (objUrl.pathname.endsWith('.ico')) {145        contType = 'image/bmp';146      }147      else if (objUrl.pathname.endsWith('.png')) {148        contType = 'image/png';149      }150      else if (objUrl.pathname.endsWith('.jpg') || objUrl.pathname.endsWith('.jpeg')) {151        contType = 'image/jpeg';152      }153      else if (objUrl.pathname.endsWith('.htm') || objUrl.pathname.endsWith('.html')) {154        contType = 'text/html';155      }156      else if (objUrl.pathname !== '/') {157        contType = 'application/octet-stream';158      }159      console.log('contType: [' + contType + '] <==============================');160      console.log('objUrl.pathname: ' + objUrl.pathname);161      //console.log('objUrl.path: ' + objUrl.path);162      if (contType === '') {  // default formNameIni e.g. indexForm.html.163        contType = 'text/html';164        console.log('Empty contType read file: ./' + dirName + '/' + formNameIni);165        fs.readFile('./' + dirName + '/' + formNameIni, (err, data) => {166          if (err) {167            res.writeHead(200, { 'Content-Type': `${contType}` });168            res.write(`Empty contType as ${dirName}/${formNameIni} not found!`);169            return res.end();170              } // throw err;171          else {172            res.writeHead(200, { 'Content-Type': 'text/html' });173            res.write(data);174            return res.end();175          }176        });177      }178      else {179        console.log('Non empty contType read file: ./' + dirName + objUrl.pathname);180        fs.readFile('./' + dirName + objUrl.pathname, (err, data) => { // './' + dirName  + "/path/name.type"181        if (err) {182          res.writeHead(200, { 'Content-Type': 'text/plain' });183          res.write(`Non empty contType ${contType} as ${dirName + objUrl.pathname} not found!`);184          return res.end();185            } // throw err;186        else {187            res.writeHead(200, { 'Content-Type': `${contType}` });188            res.write(data);189            return res.end();190          }191        });192      }193    } // end of objUrl.search === null -> no ? in GET request.194    else { // objUrl.search !== null, there is ? in GET request.195      // for req.method === "GET" objUrl.search is ? + query e.g. "?q=123-12345678-1234567" or Null if no ? in GET request.196      // req.url = "/formAK?q=123-12345678-1234567"197      /*198      req.url = "/formAK?q=123-12345678-1234567"199      ObjUrl {200      href: = path: /formNameIni?fname=al&sname=kaa"201      pathname: /formNameIni"202      search: "?fname=al&sname=kaa"203      query: {fname: "al", sname: "kaa"}204      }205      */206      // HACKER ATTACK OR FAULTY CLIENT.207      //req.connection.destroy();208      //req.url = "/formAKval?q=123-12345678-1234567"209      //console.log(objUrl.pathname); // "/formAKval"210      //console.log(objUrl.search); // "?q=123-12345678-1234567"211      if (req.url.indexOf('/formAKchk?') >= 0) {212        /*213        res.writeHead(200, { 'Content-Type': 'text/xml' });214        //res.write('');215        res.write('<?xml version="1.0" encoding="UTF-8"?>');216        res.write('<response>');217        res.write('<ticket>225-13818091-1101234</ticket>');218        res.write('<game>2</game>');219        res.write('<sum>10.00</sum>');220        res.write(`<result>0</result>`);221        res.write('</response>');222        */223        /*224        ElseIf (InStrRev(strBuf, "PPAY", -1, CompareMethod.Text) > 0) Then225        ReqStruct.sum = -1226        ElseIf (InStrRev(strBuf, "CASH", -1, CompareMethod.Text) > 0) Then227        ReqStruct.sum = -2228        ElseIf (InStrRev(strBuf, "CSHX", -1, CompareMethod.Text) > 0) Then229        ReqStruct.sum = -3230        ElseIf (InStrRev(strBuf, "VCAN", -1, CompareMethod.Text) > 0) Then231        ReqStruct.sum = -4232        ElseIf (InStrRev(strBuf, "VDEL", -1, CompareMethod.Text) > 0) Then233        ReqStruct.sum = 0234        */235        //ValTicket('225-13818091-1101234', res);236        let ticnum = '';237        //objUrl.search is e.g. "?q=123-12345678-1234567"238        ticnum = objUrl.search.slice(objUrl.search.indexOf('=') + 1);239        rawData = '';240        CheckValTicket(ticnum, res);241        //console.log(`rawData in server.on('request', (req, res) ...) event :`)242        //console.log(rawData); // will be empy ''.243        //res.write(rawData);244      } // end of if (req.url.indexOf('/formAK?') >= 0)245      //req.url = "/formAKpay?q=ticreq"246      //console.log(objUrl.pathname); // "/formAKpay"247      //console.log(objUrl.search); // "?q=ticreq"248      else if (req.url.indexOf('/formAKpay?') >= 0) {249        let ticreq = '';250        //objUrl.search is e.g. "?q=123-12345678-1234567"251        ticreq = objUrl.search.slice(objUrl.search.indexOf('=') + 1);252        rawData = '';253        BuyTicket(ticreq, res);254      }255      else {256        //res.writeHead(200, { 'Content-Type': 'text/plain' });257        //res.write(`Form request submitted by GET. Action URL with search: ${req.url}`);258        res.writeHead(200, { 'Content-Type': 'text/html' });259        res.write('<!DOCTYPE html>');260        res.write('<html lang="en">');261        res.write('<head>');262        res.write('<meta charset="utf-8" />');263        res.write('<meta name="viewport" content="width=device-width, initial-scale=1.0" />');264        res.write('<title>Unknown Form request submitted by GET</title>');265        res.write('<style>');266        res.write('#ticinfo {');267        //res.write('width: 70%;');268        res.write('margin: 3% 3% 3% 3%;');269        res.write('background-color: #dfdbdb;');270        res.write('border: thick solid black;');271        res.write('outline: dashed red;');272        res.write('}');273        res.write('#ticback {');274        res.write('display: block;')275        res.write('width: 10%;');276        res.write('margin: 3% 3% 3% 3%;');277        res.write('padding: 1% 1% 1% 1%;');278        res.write('color: white;')279        res.write('background-color: blue;');280        res.write('border: thin solid black;');281        res.write('border-radius: 15%;')282        res.write('text-decoration:none;')283        res.write('}');284        res.write('#ticket {');285        res.write('display: block;')286        res.write('margin: 3% 3% 3% 3%;');287        res.write('padding: 1% 1% 1% 1%;');288        res.write('background-color: white;');289        res.write('border: thin solid black;');290        res.write('}');291        res.write('</style>');292        res.write('</head>');293        res.write('<body>');294        res.write('<div id="ticinfo">');295        res.write('<a id="ticback" href="/">Back</a>');296        res.write('<h4>Unknown Form request submitted by GET</h4>');297        res.write(`GET action URL (form name with search included): ${req.url}`);298        res.write('</p>');299        res.write('</div>');300        res.write('</body>');301        res.write('</html>');302        res.end();303        return res.end();304      }305      //return res.end();306    }307  } // <==================== End of GET method form submit case ====================================================>308  else { // <==================== Begin of POST method form submit case ============================================>309    // POST method. NB! If req.method === "POST" then ObjUrl.search will be Null always.310    //let objUrl = urlLegacy.parse(req.url, true, true); // non standard object is got earlier befor GET or POST analyze.311    /*312    req.url = "/formNameIni"313    ObjUrl {314      href: = path: = pathname:  "/formNameIni"315      search: null316      query: Object {}317    }318    later body will be319    body: "fname=al\r\nsname=kaa\r\n"320    */321    let body = '';322    req.on('data', function (data) {323      body += data;324      // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB.325      if (body.length > 1e6) {326        // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST.327        req.connection.destroy();328      }329    });330    req.on('end', function () {331      // e.g. body = 'fname=Alex\r\nsname=Raven\r\n' for /formNameIni332      /*333      console.log(body);334      let strVar = '';335      for (let i = 0; i < body.length; i++) {336        strVar = strVar + body.charCodeAt(i) + ",";337      }338      console.log(strVar);339      */340      //console.log(objBody);341      //let objBody = qs.parse(body, "\r\n", "="); // using const qs = require('querystring') module.342      /*343        req.url = "/submitformAK"344        ObjUrl {345          href: = path: = pathname:  "/submitformAK"346          search: null347          query: Object {}348        }349        body: "fname=al\r\nsname=kaa\r\n"350        objBody: Object {fname: "al", sname: "kaa"}    }351      */352      // HACKER ATTACK OR FAULTY CLIENT.353      //req.connection.destroy();354      //res.writeHead(200, { 'Content-Type': 'text/plain' });355      //res.write(`Form request submitted by POST. Action URL is ${req.url} with search as body: \r\n${body}`);356      res.writeHead(200, { 'Content-Type': 'text/html' });357      res.write('<!DOCTYPE html>');358      res.write('<html lang="en">');359      res.write('<head>');360      res.write('<meta charset="utf-8" />');361      res.write('<meta name="viewport" content="width=device-width, initial-scale=1.0" />');362      res.write('<title>Form request submitted by POST</title>');363      res.write('<style>');364      res.write('#ticinfo {');365      //res.write('width: 70%;');366      res.write('margin: 3% 3% 3% 3%;');367      res.write('background-color: #dfdbdb;');368      res.write('border: thick solid black;');369      res.write('outline: dashed red;');370      res.write('}');371      res.write('#ticback {');372      res.write('display: block;')373      res.write('width: 10%;');374      res.write('margin: 3% 3% 3% 3%;');375      res.write('padding: 1% 1% 1% 1%;');376      res.write('color: white;')377      res.write('background-color: blue;');378      res.write('border: thin solid black;');379      res.write('border-radius: 15%;')380      res.write('text-decoration:none;')381      res.write('}');382      res.write('#ticket {');383      res.write('display: block;')384      res.write('margin: 3% 3% 3% 3%;');385      res.write('padding: 1% 1% 1% 1%;');386      res.write('background-color: white;');387      res.write('border: thin solid black;');388      res.write('}');389      res.write('</style>');390      res.write('</head>');391      res.write('<body>');392      res.write('<div id="ticinfo">');393      res.write('<a id="ticback" href="/">Back</a>');394      res.write('<h4>Form request submitted by POST</h4>');395      res.write('<p id="ticket">');396      res.write(`POST action (form name) as URL is ${req.url} with search as body: ${body}`);397      res.write('</p>');398      res.write('</div>');399      res.write('</body>');400      res.write('</html>');401      res.end();402      return res.end();403    }); // end req.on('end', function ()...404  } // <==================================== End of POST method form submit case ===================================>405}) // end of server.on('request'...)406dtVar = new Date();407console.log('After https.createServer ' + dtVar.getSeconds() + "." + dtVar.getMilliseconds());408// Begin accepting connections on the specified port and hostname.409// If hostname is omitted, server will accept connections on the unspecified IPv6 address (::) when IPv6 is available,410// or the unspecified IPv4 address (0.0.0.0) otherwise.411server.listen(port, hostname, () => {412  // Place holders in template literals are indicated by the $ (Dollar sign) and curly braces e.g. (${expression}).413  console.log(`Server running and listening at https://${hostname}:${port}/ ` + dtVar.getSeconds() + "." + dtVar.getMilliseconds()); // ${expression} is place holders in template literal enclosed by the back-tick (` `) (grave accent) characters.414});415dtVar = new Date();416console.log('End Serer main PROGAM path after server.listen(port, hostname, callback) ' + dtVar.getSeconds() + "." + dtVar.getMilliseconds());417// <==================================== ValTicket =====================================>418function CheckValTicket(ticnum, res2) {419  // reqString e.g. "http://10.8.194.3:9994/?agent=58&type=2&command=checkval&ticket_number="420  console.log(reqString + ticnum);421  http.get(reqString + ticnum, (res) => {422    const { statusCode } = res;423    const contentType = res.headers['content-type'];424    let error;425    if (statusCode !== 200) {426      error = new Error(`Request Failed.\n Status Code: ${statusCode}`);427    }428    else if (!/^text\/xml/.test(contentType)) {429      error = new Error(`Invalid content-type.\n Expected text/xml but received ${contentType}`);430    }431    if (error) {432      console.error(error.message);433      // consume response data to free up memory434      res.resume();435      //return error.message;436    }437    res.setEncoding('utf8');438    //let rawData = '';439    res.on('data', (chunk) => { rawData += chunk; });440    res.on('end', () => {441      try {442        //const parsedData = JSON.parse(rawData);443        //console.log(parsedData);444        console.log(`rawData in client http.on('end', ...) event :`)445        console.log(rawData);446        let reply;447        reply = '';448        let errmsg = '';449        parseString(rawData, function (err, result) {450            if (err !== null) {451              //console.log(err.message);452              // "Non-whitespace before first tag.\nLine: 0\nColumn: 1\nChar: ?"453              errmsg = err.message.replace('\n',' ');454              while (errmsg.indexOf('\n') !== -1) {455                errmsg = errmsg.replace('\n',' ');456              }457              //console.log(errmsg);458            }459            else {460              //console.log(result);461              reply = result;462            }463        });464        let sum = '';465        let ticinfo = '';466        if (reply !== '') {467          //console.log('reply:');468          //console.log(reply.response.result[0]);469          if (reply.response.result[0] === '0') {470            sum = reply.response.sum[0];471            //console.log('sum =' + sum);472            if (sum === '-1.00') {473              ticinfo = `ÐолÑÑой вÑигÑÑÑ!!!.`474            }475            else if (sum === '-2.00') {476              ticinfo = `ÐÐ¸Ð»ÐµÑ Ñже вÑплаÑен.`477            }478            else if (sum === '-3.00') {479              ticinfo = `ÐÐ¸Ð»ÐµÑ Ð²ÑплаÑен Ñ Ð¾Ð±Ð¼ÐµÐ½Ð½Ñм билеÑом.`480            }481            else if (sum === '-4.00') {482              ticinfo = `ÐÐ¸Ð»ÐµÑ Ð°Ð½Ð½ÑлиÑован.`483            }484            else if (sum === '0.00') {485              ticinfo = `ÐÐ¸Ð»ÐµÑ Ð½Ðµ вÑигÑал.`486            }487            else {488              ticinfo = `ÐÐ°Ñ Ð²Ð¸Ð³ÑÐ°Ñ ${sum} гÑн.`489            }490            console.log(ticinfo);491          }492          else {493            ticinfo = 'Server reply with result: ' + reply.response.result[0];494            console.log(ticinfo);495          }496        }497        else {498          ticinfo = 'XML wrong format:' + errmsg;499        }500        //res2.writeHead(200, { 'Content-Type': 'text/xml' });501        //res2.write(rawData);502        // Content-Type: text/xml; charset=UTF-8503        //res2.writeHead(200, { 'Content-Type': 'text/plain; charset=UTF-8' });504        //res2.write('Ticket info: ' + ticinfo);505        res2.writeHead(200, { 'Content-Type': 'text/html' });506        res2.write('<!DOCTYPE html>');507        res2.write('<html lang="en">');508        res2.write('<head>');509        res2.write('<meta charset="utf-8" />');510        res2.write('<meta name="viewport" content="width=device-width, initial-scale=1.0" />');511        res2.write('<title>Ticket info</title>');512        res2.write('<style>');513        res2.write('#ticinfo {');514        //res2.write('width: 70%;');515        res2.write('margin: 3% 3% 3% 3%;');516        res2.write('background-color: #dfdbdb;');517        res2.write('border: thick solid black;');518        res2.write('outline: dashed red;');519        res2.write('}');520        res2.write('#ticback {');521        res2.write('display: block;')522        res2.write('width: 10%;');523        res2.write('margin: 3% 3% 3% 3%;');524        res2.write('padding: 1% 1% 1% 1%;');525        res2.write('color: white;')526        res2.write('background-color: blue;');527        res2.write('border: thin solid black;');528        res2.write('border-radius: 15%;')529        res2.write('text-decoration:none;')530        res2.write('}');531        res2.write('#ticket {');532        res2.write('display: block;')533        res2.write('margin: 3% 3% 3% 3%;');534        res2.write('padding: 1% 1% 1% 1%;');535        res2.write('background-color: white;');536        res2.write('border: thin solid black;');537        res2.write('}');538        //res2.write('');539        res2.write('</style>');540        res2.write('</head>');541        res2.write('<body>');542        res2.write('<div id="ticinfo">');543        res2.write('<a id="ticback" href="/">Back</a>');544        res2.write('<p id="ticket">');545        res2.write(ticinfo);546        res2.write('</p>');547        res2.write('</div>');548        res2.write('</body>');549        res2.write('</html>');550        //res2.write('');551      } catch (e) {552        console.error(e.message);553        res2.writeHead(200, { 'Content-Type': 'text/html' });554        res2.write('<!DOCTYPE html>');555        res2.write('<html lang="en">');556        res2.write('<head>');557        res2.write('<meta charset="utf-8" />');558        res2.write('<meta name="viewport" content="width=device-width, initial-scale=1.0" />');559        res2.write('<title>Ticket info processing error</title>');560        res2.write('<style>');561        res2.write('#ticinfo {');562        //res2.write('width: 70%;');563        res2.write('margin: 3% 3% 3% 3%;');564        res2.write('background-color: #dfdbdb;');565        res2.write('border: thick solid black;');566        res2.write('outline: dashed red;');567        res2.write('}');568        res2.write('#ticback {');569        res2.write('display: block;')570        res2.write('width: 10%;');571        res2.write('margin: 3% 3% 3% 3%;');572        res2.write('padding: 1% 1% 1% 1%;');573        res2.write('color: white;')574        res2.write('background-color: blue;');575        res2.write('border: thin solid black;');576        res2.write('border-radius: 15%;')577        res2.write('text-decoration:none;')578        res2.write('}');579        res2.write('#ticket {');580        res2.write('display: block;')581        res2.write('margin: 3% 3% 3% 3%;');582        res2.write('padding: 1% 1% 1% 1%;');583        res2.write('background-color: white;');584        res2.write('border: thin solid black;');585        res2.write('}');586        //res2.write('');587        res2.write('</style>');588        res2.write('</head>');589        res2.write('<body>');590        res2.write('<div id="ticinfo">');591        res2.write('<a id="ticback" href="/">Back</a>');592        res2.write('<h4>Ticket info processing error</h4>');593        res2.write('<p id="ticket">');594        res2.write(e.message);595        res2.write('</p>');596        res2.write('</div>');597        res2.write('</body>');598        res2.write('</html>');599      }600      res2.end();601      //return rawData;602    });603  }).on('error', (e) => {604    // e.message e.g. "connect ETIMEDOUT 10.8.194.3:9993"605    console.error(`Got error: ${e.message}`);606    res2.writeHead(200, { 'Content-Type': 'text/html' });607    res2.write('<!DOCTYPE html>');608    res2.write('<html lang="en">');609    res2.write('<head>');610    res2.write('<meta charset="utf-8" />');611    res2.write('<meta name="viewport" content="width=device-width, initial-scale=1.0" />');612    res2.write('<title>Ticket info network error</title>');613    res2.write('<style>');614    res2.write('#ticinfo {');615    //res2.write('width: 70%;');616    res2.write('margin: 3% 3% 3% 3%;');617    res2.write('background-color: #dfdbdb;');618    res2.write('border: thick solid black;');619    res2.write('outline: dashed red;');620    res2.write('}');621    res2.write('#ticback {');622    res2.write('display: block;')623    res2.write('width: 10%;');624    res2.write('margin: 3% 3% 3% 3%;');625    res2.write('padding: 1% 1% 1% 1%;');626    res2.write('color: white;')627    res2.write('background-color: blue;');628    res2.write('border: thin solid black;');629    res2.write('border-radius: 15%;')630    res2.write('text-decoration:none;')631    res2.write('}');632    res2.write('#ticket {');633    res2.write('display: block;')634    res2.write('margin: 3% 3% 3% 3%;');635    res2.write('padding: 1% 1% 1% 1%;');636    res2.write('background-color: white;');637    res2.write('border: thin solid black;');638    res2.write('}');639    //res2.write('');640    res2.write('</style>');641    res2.write('</head>');642    res2.write('<body>');643    res2.write('<div id="ticinfo">');644    res2.write('<a id="ticback" href="/">Back</a>');645    res2.write('<h4>Ticket info network error</h4>');646    res2.write('<p id="ticket">');647    res2.write(e.message);648    res2.write('</p>');649    res2.write('</div>');650    res2.write('</body>');651    res2.write('</html>');652    res2.end();653    //return e.message;654  });655} // end of function ValTicket(ticnum, res2)656// <==================================== ValTicket =====================================>657function BuyTicket(ticreq, res2) {658  console.log(reqStringPay + ticreq);659  reqStringPay = urlpay + '?agent=65&type=2&command=pay&date=20200808&txn_id=' + txn_id + '&game=6&num_of_draws=1&num_of_boards=1&sum=15.00&msisdn=0';660  txn_id = txn_id + 1;661  http.get(reqStringPay, (res) => { // reqStringPay + ticreq for manual non-auto.662    const { statusCode } = res;663    const contentType = res.headers['content-type'];664    let error;665    if (statusCode !== 200) {666      error = new Error(`Request Failed.\n Status Code: ${statusCode}`);667    }668    else if (!/^text\/xml/.test(contentType)) {669      error = new Error(`Invalid content-type.\n Expected text/xml but received ${contentType}`);670    }671    if (error) {672      console.error(error.message);673      // consume response data to free up memory674      res.resume();675      //return error.message;676    }677    res.setEncoding('utf8');678    //let rawData = '';679    res.on('data', (chunk) => { rawData += chunk; });680    res.on('end', () => {681      try {682        let dtVar = new Date();683        //const parsedData = JSON.parse(rawData);684        //console.log(parsedData);685        console.log(`rawData in client http.on('end', ...) event :`)686        console.log(rawData);687        let reply;688        reply = '';689        let errmsg = '';690        parseString(rawData, function (err, result) {691            if (err !== null) {692              //console.log(err.message);693              // "Non-whitespace before first tag.\nLine: 0\nColumn: 1\nChar: ?"694              errmsg = err.message.replace('\n',' ');695              while (errmsg.indexOf('\n') !== -1) {696                errmsg = errmsg.replace('\n',' ');697              }698              //console.log(errmsg);699            }700            else {701              //console.log(result);702              reply = result;703            }704        });705        //let sum = '';706        let ticinfo = '';707        if (reply !== '') {708          //console.log('reply:');709          //console.log(reply.response.result[0]);710          if (reply.response.result[0] === '0') {711            //sum = reply.response.sum[0];712            //console.log('sum =' + sum);713            ticinfo = ticinfo + '<li>УкÑаÑнÑÑка ÐаÑÑоналÑна ÐоÑеÑеÑ</li>';714            ticinfo = ticinfo + '<li>ÐаÑа: ' + reply.response.ticket[0].date[0] + '</li>';715            ticinfo = ticinfo + '<li>ЧаÑ: '  + reply.response.ticket[0].time[0] + '</li>';716            ticinfo = ticinfo + '<li>ÐомбÑнаÑиÑ: '  + reply.response.ticket[0].board1a[0] + '</li>'717            ticinfo = ticinfo + '<li>СÑма: '  + reply.response.ticket[0].sum[0] + '</li>';718            ticinfo = ticinfo + '<li>ÐÐ¾Ð¼ÐµÑ Ð±ÑлеÑа: '  + reply.response.ticket[0].number[0] + '</li>';719            ticinfo = ticinfo + '<li>Ðод: '  + reply.response.ticket[0].gguard[0] + '</li>';720            ticinfo = ticinfo + '<li>txn_id: '  + reply.response.txn_id[0] + '</li>';721            console.log(ticinfo);722          }723          else {724            ticinfo = 'Server reply with result: ' + reply.response.result[0];725            console.log(ticinfo);726          }727        }728        else {729          ticinfo = 'XML wrong format:' + errmsg;730        }731        //res2.writeHead(200, { 'Content-Type': 'text/xml' });732        //res2.write(rawData);733        // Content-Type: text/xml; charset=UTF-8734        //res2.writeHead(200, { 'Content-Type': 'text/plain; charset=UTF-8' });735        //res2.write('Ticket info: ' + ticinfo);736        res2.writeHead(200, { 'Content-Type': 'text/html' });737        res2.write('<!DOCTYPE html>');738        res2.write('<html lang="en">');739        res2.write('<head>');740        res2.write('<meta charset="utf-8" />');741        res2.write('<meta name="viewport" content="width=device-width, initial-scale=1.0" />');742        res2.write('<title>Ticket info</title>');743        res2.write('<style>');744        res2.write('#ticinfo {');745        //res2.write('width: 70%;');746        res2.write('margin: 3% 3% 3% 3%;');747        res2.write('background-color: #dfdbdb;');748        res2.write('border: thick solid black;');749        res2.write('outline: dashed red;');750        res2.write('}');751        res2.write('#ticback {');752        res2.write('display: block;')753        res2.write('width: 10%;');754        res2.write('margin: 1% 3% 1% 3%;');755        res2.write('padding: 1% 1% 1% 1%;');756        res2.write('color: white;')757        res2.write('background-color: blue;');758        res2.write('border: thin solid black;');759        res2.write('border-radius: 15%;')760        res2.write('text-decoration:none;')761        res2.write('}');762        res2.write('#tichdr {');763        res2.write('margin: 1% 3% 1% 3%;');764        //res2.write('padding: 1% 1% 1% 1%;');765        res2.write('}');766        res2.write('#ticket {');767        res2.write('display: block;')768        res2.write('margin: 1% 3% 1% 3%;');769        res2.write('padding: 1% 1% 1% 1%;');770        res2.write('background-color: white;');771        res2.write('border: thin solid black;');772        res2.write('}');773        //res2.write('');774        res2.write('</style>');775        res2.write('</head>');776        res2.write('<body>');777        res2.write('<div id="ticinfo">');778        res2.write('<a id="ticback" href="/">Back</a>');779        res2.write('<h3 id="tichdr">ÐÐ°Ñ Ð±Ð¸Ð»ÐµÑ Ð·Ð°ÑегиÑÑÑиÑован: ' + dtVar.toLocaleString() + '</h3>');780        res2.write('<ul id="ticket">');781        res2.write(ticinfo);782        res2.write('</ul>');783        res2.write('</div>');784        res2.write('</body>');785        res2.write('</html>');786        //res2.write('');787      } catch (e) {788        console.error(e.message);789        res2.writeHead(200, { 'Content-Type': 'text/html' });790        res2.write('<!DOCTYPE html>');791        res2.write('<html lang="en">');792        res2.write('<head>');793        res2.write('<meta charset="utf-8" />');794        res2.write('<meta name="viewport" content="width=device-width, initial-scale=1.0" />');795        res2.write('<title>Ticket info processing error</title>');796        res2.write('<style>');797        res2.write('#ticinfo {');798        //res2.write('width: 70%;');799        res2.write('margin: 3% 3% 3% 3%;');800        res2.write('background-color: #dfdbdb;');801        res2.write('border: thick solid black;');802        res2.write('outline: dashed red;');803        res2.write('}');804        res2.write('#ticback {');805        res2.write('display: block;')806        res2.write('width: 10%;');807        res2.write('margin: 3% 3% 3% 3%;');808        res2.write('padding: 1% 1% 1% 1%;');809        res2.write('color: white;')810        res2.write('background-color: blue;');811        res2.write('border: thin solid black;');812        res2.write('border-radius: 15%;')813        res2.write('text-decoration:none;')814        res2.write('}');815        res2.write('#ticket {');816        res2.write('display: block;')817        res2.write('margin: 3% 3% 3% 3%;');818        res2.write('padding: 1% 1% 1% 1%;');819        res2.write('background-color: white;');820        res2.write('border: thin solid black;');821        res2.write('}');822        //res2.write('');823        res2.write('</style>');824        res2.write('</head>');825        res2.write('<body>');826        res2.write('<div id="ticinfo">');827        res2.write('<a id="ticback" href="/">Back</a>');828        res2.write('<h4>Ticket info processing error</h4>');829        res2.write('<p id="ticket">');830        res2.write(e.message);831        res2.write('</p>');832        res2.write('</div>');833        res2.write('</body>');834        res2.write('</html>');835      }836      res2.end();837      //return rawData;838    });839  }).on('error', (e) => {840    // e.message e.g. "connect ETIMEDOUT 10.8.194.3:9993"841    console.error(`Got error: ${e.message}`);842    res2.writeHead(200, { 'Content-Type': 'text/html' });843    res2.write('<!DOCTYPE html>');844    res2.write('<html lang="en">');845    res2.write('<head>');846    res2.write('<meta charset="utf-8" />');847    res2.write('<meta name="viewport" content="width=device-width, initial-scale=1.0" />');848    res2.write('<title>Ticket info network error</title>');849    res2.write('<style>');850    res2.write('#ticinfo {');851    //res2.write('width: 70%;');852    res2.write('margin: 3% 3% 3% 3%;');853    res2.write('background-color: #dfdbdb;');854    res2.write('border: thick solid black;');855    res2.write('outline: dashed red;');856    res2.write('}');857    res2.write('#ticback {');858    res2.write('display: block;')859    res2.write('width: 10%;');860    res2.write('margin: 3% 3% 3% 3%;');861    res2.write('padding: 1% 1% 1% 1%;');862    res2.write('color: white;')863    res2.write('background-color: blue;');864    res2.write('border: thin solid black;');865    res2.write('border-radius: 15%;')866    res2.write('text-decoration:none;')867    res2.write('}');868    res2.write('#ticket {');869    res2.write('display: block;')870    res2.write('margin: 3% 3% 3% 3%;');871    res2.write('padding: 1% 1% 1% 1%;');872    res2.write('background-color: white;');873    res2.write('border: thin solid black;');874    res2.write('}');875    //res2.write('');876    res2.write('</style>');877    res2.write('</head>');878    res2.write('<body>');879    res2.write('<div id="ticinfo">');880    res2.write('<a id="ticback" href="/">Back</a>');881    res2.write('<h4>Ticket info network error</h4>');882    res2.write('<p id="ticket">');883    res2.write(e.message);884    res2.write('</p>');885    res2.write('</div>');886    res2.write('</body>');887    res2.write('</html>');888    res2.end();889    //return e.message;890  });...binaryCalculator.js
Source:binaryCalculator.js  
1/*For Binary Calculator*/2function fnCalSum(dno1,dno2){3    let sum=dno1+dno2;4    res.innerHTML=sum.toString(2);5}6function fnCalSub(dno1,dno2){7     let sub=dno1-dno2;8    res.innerHTML=sub.toString(2);9}10function fnCalMul(dno1,dno2){11    let mul=dno1*dno2;12    res.innerHTML=mul.toString(2);13}14function fnCalDiv(dno1,dno2){15    let div=dno1/dno2;16    res.innerHTML=div.toString(2);17}18function fnToDec(no1,no2,ch){19    let dn1=0,dn2=0;20    let i=0;21    22    while(no1!=0){23        let a=no1%10;24        dn1+=a*(2**i);25        no1=parseInt(no1/10);26        i++;27    }28    i=0;29    while(no2!=0){30        let a=no2%10;31        dn2+=a*(2**i);32        no2=parseInt(no2/10);33        i++;34    }35    36    if(ch=='+') {37        fnCalSum(dn1,dn2);38    }39    else if(ch=='-') {40        fnCalSub(dn1,dn2);41    }42    else if(ch=='*') {43        fnCalMul(dn1,dn2);44    }45    else if(ch=='/') {46        fnCalDiv(dn1,dn2);47    }48}49function fnad0() {50    let res=document.getElementById('res');51    res.innerHTML +=0;52}53function fnad1(){54     let res=document.getElementById('res');55    res.innerHTML+=1;56}57function fnClr(){58    let res=document.getElementById('res');59    res.innerHTML='';60}61function fnEql(){62    let res=document.getElementById('res');63        try{64            if(res.innerHTML.includes('+')){        65               let operand=res.innerHTML.split('+');66                let n1=Number(operand[0]);67                let n2=Number(operand[1]);68                 69                fnToDec(n1,n2,'+');70               71                72                73             }74            else if(res.innerHTML.includes('-')){        75               let operand=res.innerHTML.split('-');76                let n1=Number(operand[0]);77                let n2=Number(operand[1]);78                fnToDec(n1,n2,'-');79            }80            else if(res.innerHTML.includes('*')){        81               let operand=res.innerHTML.split('*');82                let n1=Number(operand[0]);83                let n2=Number(operand[1]);84                fnToDec(n1,n2,'*');85            }86            else if(res.innerHTML.includes('/')){        87               let operand=res.innerHTML.split('/');88                let n1=Number(operand[0]);89                let n2=Number(operand[1]);90                fnToDec(n1,n2,'/');91            }92        }93        catch(e){94            res.innerHTML=e.message;95        }96}97function fnadSum(){98    let res=document.getElementById('res');99    res.innerHTML+='+';100}101function fnadSub(){102    let res=document.getElementById('res');103    res.innerHTML+='-';104}105function fnadMul(){106    let res=document.getElementById('res');107    res.innerHTML+='*';108}109function fnadDiv(){110    let res=document.getElementById('res');111    res.innerHTML+='/';112}113/*For Normal Calculator*/114function f1(){115    res2=document.getElementById('res2');116    res2.innerHTML+=1;117}118function f2(){119    res2=document.getElementById('res2');120    res2.innerHTML+=2;121}122function f3(){123    res2=document.getElementById('res2');124    res2.innerHTML+=3;125}126function fClr(){127    res2=document.getElementById('res2');128    res2.innerHTML="";129}130function fDel(){131}132function f4(){133    res2=document.getElementById('res2');134    res2.innerHTML+=4;135}136function f5(){137    res2=document.getElementById('res2');138    res2.innerHTML+=5;139}140function f6(){141    res2=document.getElementById('res2');142    res2.innerHTML+=6;143}144function f7(){145    res2=document.getElementById('res2');146    res2.innerHTML+=7;147}148function f8(){149    res2=document.getElementById('res2');150    res2.innerHTML+=8;151}152function f9(){153    res2=document.getElementById('res2');154    res2.innerHTML+=9;155}156function f0(){157    res2=document.getElementById('res2');158    res2.innerHTML+=0;159}160function fEql(){161    let res2=document.getElementById('res2');162        try{163            if(res2.innerHTML.includes('+')){        164               let operand=res2.innerHTML.split('+');165                let n1=Number(operand[0]);166                let n2=Number(operand[1]);167                res2.innerHTML=n1+n2;             168            }169            else if(res2.innerHTML.includes('-')){        170               let operand=res2.innerHTML.split('-');171                let n1=Number(operand[0]);172                let n2=Number(operand[1]);173                res2.innerHTML=n1-n2;174                175            }176            else if(res2.innerHTML.includes('*')){        177               let operand=res2.innerHTML.split('*');178                let n1=Number(operand[0]);179                let n2=Number(operand[1]);180                res2.innerHTML=n1*n2;181                182            }183            else if(res2.innerHTML.includes('/')){        184               let operand=res2.innerHTML.split('/');185                let n1=Number(operand[0]);186                let n2=Number(operand[1]);187                res2.innerHTML=n1/n2;188            }189            else if(res2.innerHTML.includes('%')){        190               let operand=res2.innerHTML.split('%');191                let n1=Number(operand[0]);192                let n2=Number(operand[1]);193                res2.innerHTML=n1%n2;194            }195            else{                196               res2.innerHTML="<h6>SORRY FOR TWO OPERANDS ONLY</h6>"; 197            }198        }199        catch(e){200            res2.innerHTML=e.message;201        }202}203function fSum(){204    let res2=document.getElementById('res2');205    res2.innerHTML+='+';206}207function fSub(){208    let res2=document.getElementById('res2');209    res2.innerHTML+='-';210}211function fMul(){212    let res2=document.getElementById('res2');213    res2.innerHTML+='*';214}215function fDiv(){216    let res2=document.getElementById('res2');217    res2.innerHTML+='/';218}219function fMod(){220let res2=document.getElementById('res2');221    res2.innerHTML+='%';...Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3  if (err) return console.error(err);4  console.log(data);5  wpt.getTestResults(data.data.testId, function(err, data) {6    if (err) return console.error(err);7    console.log(data);8  });9});Using AI Code Generation
1var wpt = require('webpagetest');2var options = {3};4var wpt = new WebPageTest('www.webpagetest.org', options);5wpt.runTest(url, {6}, function(err, data) {7    if (err) return console.error(err);8    console.log('Test %s from %s completed', data.data.testId, data.data.from);9    wpt.getTestResults(data.data.testId, function(err, data) {10        if (err) return console.error(err);11        console.log('Test %s from %s completed', data.data.testId, data.data.from);12    });13});14#### runTest(url, options, callback)15#### getTestResults(testId, callback)16#### getTestStatus(testId, callback)17#### getTestLocation(location,Using AI Code Generation
1var wpt = require('webpagetest');2var webpagetest = new wpt('www.webpagetest.org', 'A.1c7d9f8b8e0a3a4a5c6e7f8g9h0a1b2c3');3}, function(err, data) {4    if (err) return console.error(err);5    console.log('Test status: ' + data.statusText);6    if (data.statusCode === 200) {7        console.log('Test completed in ' + data.data.average.firstView.loadTime + 'ms');8    }9});10webpagetest.getTestResults(150529_4A_4e8f4c1b4e9e9f2f4c8c2e4d4f4a4d4, function(err, data) {11    if (err) return console.error(err);12    console.log('Test status: ' + data.statusText);13    if (data.statusCode === 200) {14        console.log('Test completed in ' + data.data.average.firstView.loadTime + 'ms');15    }16});Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
