web framework express learning two

let express = require("express");
let fs = require("fs");
let http = require("http");
let path = require("path");
let bodyParser = require("body-parser");
let app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.set("view engine", "ejs");
app.set("views", path.resolve(__dirname, "../views"));

// Cookie is provided with the analytical 
// CNPM Parser -S-Cookie I 
// CNPM I Signature -S-Cookie 
var cookieParser = the require ( "Cookie-Parser" );
 var Signature = the require ( "Cookie-Signature" );
 // initialization middleware, specify a Secret, string, whether the person being given 
// app.use (cookieParser ( "secrettt")); 
// app.use ((REQ, RES, Next) => { 
//    IF (REQ == .url "/ Cookie") { 
//      ! IF (req.cookies.nick) { 
//        res.cookie ( "Nick", "Qin"); // api method comes Express, express will be fill in the set-cookie Response Header, reaching set a cookie in the browser in action 
//       res.cookie ( "snick", "qin ", {signed: true}); // signed cookie can be set to true signature encryption is provided by a direct response to a browser cookie 
//        // Options {} 
//        / / domain: cookie domain name under which effective type String ,. The default is the domain 
//        // the Expires: the cookie expiration time, type Date. If not set or set to 0, then the session cookie is only valid in this, this, that is, close your browser, the cookie will be deleted browser. 
//        // httpOnly: can only be accessed by web server, type Boolean. 
//        // maxAge: achieve expires functions, set the cookie expiration time of type String, specify from now, after how many milliseconds, cookie expires. 
//        // path: Under what path the cookie is valid, the default is '/', of type String 
//        // Secure: can only be used by HTTPS, type Boolean, defaults to false 
//        // Signed: use a signature, type boolean, default is false. `express will be used to complete the signature req.secret need cookie-parser used in conjunction with` 
//       // res.clearCookie (name [, options] ); // express api provided directly delete browser Cookie 
//        the console.log (req.cookies); // {Nick: 'Qin'} unsigned Cookie stored in req.cookies 
//        the console.log (req.signedCookies); // [Object: the prototype null] {snick: Signed to false} Cookie stored only in the req.signedCookies 
//      } the else { 
//        the console.log (req.headers .cookie); // Nick = Qin; snick 3Aqin.poXxfblxvUOPCqcx07XzPtNqBu1esp% S =% 2BNfHSogg8lfc4 
//        // parse the signature 
//        // = the let sinedvalue SignedCookie ( 
//        // req.headers.cookie.split ( "=" ) [. req.headers.cookie.split ( "=") length -. 1], 
//        // "secrettt" 
//        //);
//       Be extended // 
//      } 
//      res.end ( "qinhuansky the Hello"); 
//    } the else { 
//      res.end ( "404"); 
//    } 
// }); 
// Cookie is provided with the analytical = ================================================== ========

// logging tool log4js, we will discuss later Morgan, can choose to use 
// CNPM I log4js -S 
const = log4js the require ( "log4js" );
 // logger.level = 'debug'; // set the level below debug will not print 
// configure log4js target configuration method, internal levels, appenders (file input source), the Categories three attributes 
log4js.configure ({
  appenders: {
    allLog: {
      type: "file",
      filename: "./log/all.log",
      keepFileExt: true,
      MaxLogSize: 10485760 ,
      backups: 3
    },
    "rule-console": {
      type: "console"
    },
    "rule-file": {
      type: "dateFile",
      filename: "log/server-",
      encoding: "utf-8",
      MaxLogSize: 10000000 ,
      numBackups: 3,
      pattern: "yyyy-MM-dd.log",
      alwaysIncludePattern: true
    },
    "rule-http-error": {
      type: "dateFile",
      filename: "log/error-",
      encoding: "utf-8",
      MaxLogSize: 10 * 1000 * 1000, // represents the file will be created when the next big file, in bytes, not recommended greater than 100Mb 
      numBackups: 3, // number of files backed up, if too many files would be most delete the old 
      pattern: "yyyy-MM-dd.log" ,
      alwaysIncludePattern: to true  // default ture open pattern, false is not open pattern, is not open datefile file will not have any time suffix, it will not divide files 
    }
  },
  categories: {
    default: {
      appenders: ["allLog", "rule-console", "rule-file", "rule-http-error"],
      level: "debug"
    },
    http: {
      appenders: ["rule-console"],
      level: "info"
    }
  }
});
// the getLogger parameter takes item categories, blank or other item Default value takes default 
const = Logger log4js.getLogger ();
HTTPLOG const = log4js.getLogger ( "HTTP" );
 // bit level from low to high, only the log configuration level greater than or equal to the output of information out, can effectively control the log output level by category 
// logger.trace ( " Testing Entering "); 
// logger.debug (" Got Access. "); 
// logger.info (" Access IS Comté ");. 
// logger.warn (" Access IS quite Smelly ");. 
// Logger .error ( "Access IS TOO RIPE!"); 
// logger.fatal ( "Access WAS Breeding Ground for listeria."); 
httpLog.info ( "I can print out" );
httpLog.debug ( "my info below a set level, do not print out" );
 // [2019-12-26T13: 17: 02.443] [INFO] HTTP - I can print it out 
// https://github.com / log4js-the Node / log4js the Node- 
// logging tool log4js ===================================== ============================

// theory section of crypto modules 
// summary (digest): The fixed length message as input, by running a hash function, to generate fixed-length output, this output is called a summary. Typically used to verify message integrity, it has not been tampered digest is irreversible. Common digest algorithm: MD5: 128 bit, SHA-1: 160 bit, SHA256: 256 bit, SHA512: 512 bit 
var Crypto = the require ( "Crypto" );
 var MD5 = crypto.createHash ( "MD5" );
 var Message = "Hello" ;
 var Digest = md5.update (Message, "UTF8") Digest ( "hex." );
the console.log (Digest); // 5d41402abc4b2a76b9719d911017c592 
// the HMAC (the Hash-based the Message the Authentication Code): message authentication code, can be roughly understood as a hash function with a secret key. 
// with keys keys 
the let crypto.createHmac = HMAC ( "MD5", "123456" );
let ret = hmac.update("hello").digest("hex");
the console.log (RET); // 9c699d7af73a49247a239cb0dd2f8139 
// encryption / decryption: given plaintext, through a certain algorithm to produce encrypted ciphertext, a process called encryption. In turn, it is decrypted. 
// The encryption and decryption keys are the same with the encryption algorithm can be divided into symmetric encryption (DES, 3DES, AES, Blowfish , RC5, IDEA), asymmetric encryption (RSA, DSA, ElGamal). 
// 1, symmetric encryption is faster than asymmetric encryption. 
// 2, asymmetric encryption is typically used to encrypt a short text, typically used to encrypt the symmetric encryption long text 
// theory part ===================== crypto modules, ============================================

// NodeJS core module, the stream is substantially Examples 
// Way a 
// fs.readFile ( "../ named text.txt in", "UTF8", function (ERR, Content) { 
//    the console.log ( "read complete file, the file content [% S]", content); 
// }); 
// Way two 
// var readStream = fs.createReadStream ( "../ named text.txt in"); 
// var = Content ""; 
// readStream.setEncoding ( "UTF8"); 
// readStream.on ( "Data", function (the chunk) { 
//    Content + = the chunk; 
// }); 
// readStream.on ( " End ", function (the chunk) { 
//    the console.log (" complete document reading, the document is [% s] ", content) ;
// });
// way 三 大文件流
// var filepath = "../text.txt";
// // 写入
// var contentText = "hello world";
// var writeStram = fs.createWriteStream(filepath);
// writeStram.write(contentText);
// writeStram.end();
// // 读出
// let fileStream = fs.createReadStream(filepath);
// fileStream.pipe(process.stdout);
// fileStream.on("data", endFun);
// function endFun() {
//   process.stdout.write("]");
// }
// process.stdout.write("文件内容: [");

@ Long polling: polling timing is improved and enhanced, the purpose is to reduce the network transmission invalid. When the server is no data update, the connection will remain for some period of time until the data or status change or time expired, the interaction between the few invalid client and server 
// streams: page using a client a hidden window sent to the server a long connection request. To respond after receiving the request and the server is updated with the state to ensure that the client and server side of the connection, but 
// the WebSocket protocol is essentially a TCP-based protocols. (Client Sec-WebSocket-Key and server-side Sec-WebSocket-Accept handshake authentication information) 
// Duplex Stream net.Socket instance 
// ==================== ============================================ 
// server 
// NodeJS the install-WebSocket --save CNPM 
// var WS = the require ( "NodeJS-WebSocket"); 
// the console.log ( "connection will be established ..."); 
// var Server WS = 
//    .createServer (function (Conn) { 
//     conn.on ( "binary", function (inStream) { 
//        // Create an empty buffer objects, binary data collected 
//        var = new new Data Buffer (0); 
//        // read the contents of binary data and added to the in buffer 
//        inStream.on ( "readable's", function () { 
//          var newData inStream.read = (); 
//          IF (newData) 
//            Data Buffer.concat = ([Data, newData], data.length newData.length +); 
//        }); 
//        inStream.on ( "End", function () { 
//          // binary read completion data, binary data 
//        }); 
//      }); 
/ /      conn.on ( "text",function(result) {
//       the console.log ( "information is received:" Result +); 
//        conn.sendText (Result, () => { 
//          the console.log ( "successfully sent"); 
//        }); 
//        // connection.send (data, [callback]) comprising sendText texting, sendBinary send binary 
//      }); 
//      // create a new link (after completion of the handshake) trigger, conn instance of an object is connected 
//      conn.on ( " connect ", function (code) { 
//        console.log (" open connection ", code); 
//      }); 
//      // this event is triggered when the service is closed, if there is any connection to maintain a link, will not the triggering event 
//      conn.on ( "Close", function (code, reason) { 
//        the console.log ( "close connection"); 
//      });
//     conn.on ( "error", function (code, reason) { 
//        the console.log ( "Exception Close"); 
//      }); 
//    }) 
//    .listen (3800); 
// the console.log ( "WebSocket establish complete"); 
// begin to establish a connection ... 
// the WebSocket establish complete 
// information received is: even on the ...... 
// information received is: Tue Dec 31 2019 15:40:29 GMT + 0800 (China standard time) can talk to the ...... 
// client 
/ * <Script>
    if(window.WebSocket){
        var ws = new WebSocket('ws://127.0.0.1:3800');
        ws.onopen = function(e){
          console.log ( "successfully connect to the server");
          ws.send ( "even on ......");
        }
        ws.onclose = function(e){
          the console.log ( "Server off");
        }
        ws.onerror = function(){
          the console.log ( "Connection error");
        }
        ws.onmessage = function(e){
          was h = new Date ();
          // ws.send (time + "connection ......");
          document.getElementById("mess").onclick = function(){
            ws.send (time + "can talk up ......");
          }
        }
    }
</script> */

// Get the file extension 
var filepath = "/tmp/demo/js/test.js" ;
 // Output: / tmp / Demo / JS 
the console.log (path.dirname (filepath));
 // Output: .js 
the console.log (path.extname (filepath));
 // output: the test.js 
the console.log (path.basename (filepath));
 // output: Test 
the console.log (path.basename (filepath, ".js" ));
 // ============================================= ===================================== 
// file read line by line: For example, a log analysis . 
// auto-complete: such as input npm, automatically prompts "help init install". 
// command line tool: Q of this example npm init formula scaffolding tool 
// const = the require the readline ( "the readline"); 
//rl is an readline.createInterface = const ({ 
//    INPUT: process.stdin, 
//    Output: process.stdout 
// }); 
// rl.question ( "Please INPUT A Word:", function (answer) { 
//    Console .log ( "entered by You have have [% S]", answer.toUpperCase ()); 
//    rl.close (); 
// }); 
// =============== ================================================== ==================== 
// Process node is a global module, more intuitive action. Can be obtained node information related to the process by which 
// environment variable: process.env 
// asynchronous: process.nextTick (the Fn) 
// get command line arguments: process.argv 
process.argv.forEach ( function(val, index, array) {
  console.log("参数" + index + ": " + val);
});
// Get node specific parameters: process.execArgv 
http.createServer (App) .listen (3800);

Guess you like

Origin www.cnblogs.com/chuanq/p/12125220.html