nodejs01 - installation and use, server and client, commonjs specification, use of fs module (file operation and directory operation), stream and buffer

Installation and use of nodejs
Server and client
commonjs specification
Use of fs module (file operation and directory operation)
stream
buffer

//

Node.js introduction

Node.js was born in 2009, node JS is written in C + + language and is a JavaScript running environment. Node.js is a JavaScript running environment based on Chrome V8 engine, which makes JavaScript run away from the browser side, and can use JavaScript language to write server-side code.

Install node js

Node.js official website Download the stable version. The even version of node is the stable version, and the odd version is the unstable version.

  • Install mac directly or brew

  • After installing node JS will automatically install NPM(Node Package Manager): package management tool;

  • Open the terminal cmd and check whether the installation is completed by instructing node -v (the installation is completed when the version number appears)

  • View the node version number; npm -v to view the npm version

Initial experience of nodejs: create a server with nodejs

index.js
//Introduce http module
let http = require("http");
//Create a server
let serve = http.createServer((req,res)=>{
    console.log("hello");
    res.write("hello");
    res.end("hello world");
})
//Set port number
serve.listen(3000);

index.js can start the service through node, node + index JS path
Access localhost:3000 (server side) through the browser
Another computer access under the same LAN is the client

Install - nomon # nomon #
nodemon automatically refreshes the node service without Ctrl+C twice

- Google Chrome Default list of non secure ports. Try to avoid the following ports.

    1,    // tcpmux
    7,    // echo
    9,    // discard
    11,   // systat
    13,   // daytime
    15,   // netstat
    17,   // qotd
    19,   // chargen
    20,   // ftp data
    21,   // ftp access
    22,   // ssh
    23,   // telnet
    25,   // smtp
    37,   // time
    42,   // name
    43,   // nicname
    53,   // domain
    77,   // priv-rjs
    79,   // finger
    87,   // ttylink
    95,   // supdup
    101,  // hostriame
    102,  // iso-tsap
    103,  // gppitnp
    104,  // acr-nema
    109,  // pop2
    110,  // pop3
    111,  // sunrpc
    113,  // auth
    115,  // sftp
    117,  // uucp-path
    119,  // nntp
    123,  // NTP
    135,  // loc-srv /epmap
    139,  // netbios
    143,  // imap2
    179,  // BGP
    389,  // ldap
    465,  // smtp+ssl
    512,  // print / exec
    513,  // login
    514,  // shell
    515,  // printer
    526,  // tempo
    530,  // courier
    531,  // chat
    532,  // netnews
    540,  // uucp
    556,  // remotefs
    563,  // nntp+ssl
    587,  // stmp?
    601,  // ??
    636,  // ldap+ssl
    993,  // ldap+ssl
    995,  // pop3+ssl
    2049, // nfs
    3659, // apple-sasl / PasswordServer
    4045, // lockd
    6000, // X11
    6665, // Alternate IRC [Apple addition]
    6666, // Alternate IRC [Apple addition]
    6667, // Standard IRC [Apple addition]
    6668, // Alternate IRC [Apple addition]

    6669, // Alternate IRC [Apple addition]


modularization

1, Why is there modularity

  • In the early days of JavaScript development, it was to realize simple page interaction logic. A few words, that is, now with the increasing expansion of front-end code

    At this time, the positioning of JavaScript as an embedded scripting language is shaken, but JavaScript does not provide any obvious help for organizing code. The extremely simple code organization specification of JavaScript is not enough to control such a large-scale code;

2, Node Modular commonjs specification in JS
(Node.js modular commonjs specification: there is no variable pollution and the file is independent)

  • CommonJS is to formulate specifications for the performance of JS. Because JS has no module function, CommonJS came into being. It hopes that JS can run anywhere, not just in the browser.

    1. Create custom module

    • Introduce a file form module

      home.js execution file

      console.log("I am home.js");
      //Import through require
      require("./aModule"); //Note that there must be ". /", and the file suffix can be added or not.
      console.log(a);//undefined, files are independent of each other to prevent variable pollution and improve readability
      

      amodule.js file

      console.log("I am amodule Module 111");
      let a = 20;
      
    • Introduction of folder form module

      • home.js execution file
      require("./aModuledir"); //". /" must be added
      

      Index in aModuleDir JS file, it will automatically find the index JS file execution

      console.log("I am aModule Module folder");
      
      • Of course, you can also configure the default startup file and create a new package in the folder JSON to specify the execution file
      {
        "name":"aModule",
        "version":"1.0.0",
        "main":"test.js"
      }
      
  • On demand export of custom modules

    Through module Exports export___ dirname , __filename

    module.exports = {
        a:"I am a Value of",
        b(){
            console.log("I exported it b function");
        }
    }
    

    Import export file

    let mymodule = require("bModule");
    console.log(mymodule.a);
    mymodule.b();
    

    Or export through exports

    exports.fn = function(){
        console.log("I am fn function");  
    }
    

    Import file

    let myfn = require("bModule").fn;
    myfn();
    // Or assignment by deconstruction 
    let { fn } = require("bModule");
    fn();
    
  • Priority of module loading, first file and then directory;

///

console.log("I am Ma.js file");
require("./Mb");
let a = 10;
class Person {
    constructor() {
        this.name = "Zhang San";
    }
    hobby() {
        console.log("Like basketball");
    }
}

// Export on demand: module export
// module.exports = {
//     a,
//     Person
// }

// Export on demand: single export
exports.a = a;
exports.Person = Person;
// Exports is module The reference of exports, that is, module exports = exports;

// AMD sea.js  CMD require.js
console.log("I am index.js");
let Ma = require("./Ma");
// console.log(a);
console.log(Ma.a);

// let cai = new Ma.Person();
// cai.hobby();

// require("./home");// Import and execute files in the home folder

// node_modules: not required/ The following requires ("mytest")
// let { a, b } = require("mytest");
// console.log(a);
// b();

// require("mytest")
// const http = require("http");

// npm: Package Manager
// dependencies: running depends on jquery, vue and react;
// devDependencies: development depends on sales less;

// Create node server
// const http = require("http");//http is a built-in module. It can be understood that HTTP is built after installing node
// const serve = http.createServer((req, res) => {
//     res.write("hello world111");
//     res.end();
// });
// serve.listen(3000);

//

2. Built in module;

nodejs built-in Modules include: Buffer, C / C + + additions, Child Processes, Cluster, Console, Crypto, Debugger, DNS, Domain, Errors, Events, File System, Globals, HTTP, HTTPS, Modules, Net, OS, Path, Process, P, unycode, Query Strings, Readline, REPL, Stream, String Decoder, Timers, TLS/SSL, TTY, UDP/Datagram, URL, Utilities, V8, VM,ZLIB;

The built-in module does not need to be installed, and the external module needs to be installed;

npm package manager (module manager)

The address of NPM(Node Package Manager) official website is npm official website

  • npm common instructions;
    • npm init: boot to create a package JSON file
    • npm help(npm -h): View npm help information
    • npm version (npm -v): view the npm version;
    • npm search: find
    • npm install (npm i): the default installation is in the current directory. If there is no node_modules will create a folder;
      • npm install module_name -S or – save, NPM install module_ Write dependencies to save dependencies --
      • npm install module_name -D or - save dev, i.e. NPM install module_ Name -- save dev write dev dependencies development dependencies
      • npm install module_name -g global installation (command line)
      • Specify the version of the installation module npm i module_name @1.0 is specified by "@" symbol;
    • npm update(npm -up): update
    • npm remove or npm uninstall: delete
    • npm root can view the installation path of the current package or view the global installation path through npm root -g;

fs module

  • fs is a file operation module. All file operations can be divided into synchronous and asynchronous. The feature is that synchronization will add "Sync", such as asynchronous reading of file "readFile" and synchronous reading of file "readFileSync";

    File operation

    • File read:

      • Asynchronous read
      let fs = require("fs");
      fs.readFile("1.txt",(err,data)=>{
          if(err){
              return console.log(err);
          }
          console.log(data.toString());
      })
      

      The first parameter is the path to read the file;
      The second parameter is the read encoding format; (can be omitted without writing) utf8
      The third parameter is the callback function;

      • Read files synchronously
      let fs = require("fs");
      let res = fs.readFileSync("1.txt");
      console.log(res.toString());
      

You need to get the return value for synchronization;
Asynchronous callback function needs to get the result;

  • File write:

    let fs = require("fs");
    //flag configuration "a": append write, "w": write, "r": read
    fs.writeFile("2.txt","What I want to write",{flag:"w"},err=>{
        if(err){
            return console.log(err);
        }
        console.log("Write successful");   
    })
    
  • File deletion

    fs.unlink("2.txt",err=>{
        if(err){
            return console.log(err);
        }
        console.log("Deleted successfully");
    })
    
  • Copy file

    • Read the file before writing it
    function mycopy(src,dest){//src: read path; dest: write path
       fs.writeFileSync(dest,fs.readFileSync(src));
    }
    mycopy("1.txt","4.txt");
    
fs.copyFile("index.html","myindex.html",err=>{
     if(err){
         return console.log(err);
     }
     console.log("Copy succeeded!");
 })
  • You can also modify the file name and directory through rename
  fs.rename("1.txt","5.txt",function (err) {
        if(err){
            console.log(err);
        }else{
            console.log("Modified successfully");
        }
    });
  • Determine whether the file exists
  fs.exists("4.txt",function (exists) {
        console.log(exists);
  })
const fs = require("fs"); //File operation
// Add, delete, modify and check;
// 1. File operation 2 Directory operation;

// File operation
// fs.writeFile("1.txt", "I am writing text", function(err){
//     if(err){
//         return console.log(err);
//     }
//     console.log("write succeeded");
// })

// The third parameter (configuration item) a: add write; w write; r: Read;
// fs.writeFile("1.txt", "I am the additional text", {flag:"a"},function(err){
//     if(err){
//         return console.log(err);
//     }
//     console.log("write succeeded");
// })

// File reading
// fs.readFile("1.txt","utf8",(err,data)=>{
//     if(err){
//         return console.log(err);
//     }
//     console.log(data);
// })
// fs.readFile("1.txt",(err,data)=>{
//         if(err){
//             return console.log(err);
//         }
//         console.log(data.toString());
//     })

// All file operations without Sync are asynchronous, otherwise they are synchronous;
// let data = fs.readFileSync("1.txt");
// console.log(data.toString());

// Modification; (change the name);
// fs.rename("1.txt","2.txt",err=>{
//     if(err){
//         return console.log(err);
//     }
//     console.log("modified successfully");
// });

// Delete;
// fs.unlink("2.txt",(err)=>{
//     if(err){
//         return console.log(err);
//     }
//     console.log("deletion succeeded");
// })

// Reproduction; The process of reading and writing first;
// fs.copyFile("index.html","myindex.html",err=>{
//     if(err){
//         return console.log(err);
//     }
//     console.log("copy succeeded!");
// })

// copy
// function mycopy(src,dest){
//    fs.writeFileSync(dest,fs.readFileSync(src));
// }
// mycopy("index.html","test.html");

// Directory operation
// Create directory
// fs.mkdir("11",err=>{
//     if(err){
//         return console.log(err);
//     }
//     console.log("created successfully");
// })

// Modify directory name
// fs.rename("11", "22", err => {
//     if (err) {
//         return console.log(err);
//     }
//     console.log("modified successfully");
// })

// Read the directory;
// fs.readdir("22",(err,data)=>{
//     if(err){
//         return console.log(err);
//     }
//     console.log(data);
// })

// Delete directory (empty folder / directory)
// fs.rmdir("11",err=>{
//     if(err){
//         return console.log(err);
//     }
//     console.log("deletion succeeded");
// })

// Determine whether the file or directory exists
// fs.exists("index.html",exists=>{
//     console.log(exists);
// })

// Obtain the detailed information of the file or directory;
// fs.stat("index.html",(err,stat)=>{
//     if(err){
//         return console.log(err);
//     }
//     // console.log(stat);
//     //Determine whether the file is a file
//     // let res = stat.isFile();
//     //Whether it is a folder;
//     let res = stat.isDirectory();
//     console.log(res);
// })

// Encapsulate and delete non empty folders;
// First delete the files in the directory -- > delete the empty directory;
// 22
function removeDir(path) {
    let data = fs.readdirSync(path);
    // ["33","1.txt","2.html"];
    for (let i = 0; i < data.length; i++) {
        // Is it a file or directory; --- >? Delete files directly? Continue to search the directory;  
        let url = path + "/" + data[i];
        let stat = fs.statSync(url);
        if (stat.isDirectory()) {
            //Continue to search the directory;
            removeDir(url);//Recursive deletion
        } else {
            // File deletion
            fs.unlinkSync(url);
        }
    }
    //  remove empty directories
    fs.rmdirSync(path);
}
removeDir("22");//Execute delete non empty folder

Buffer buffer

  • Creation of buffer
    • Create directly
    • Array creation
    • String creation
    • Processing of garbled code
    • buffer conversion tostring
// buffer creation
// new Buffer()
// let buffer = Buffer.alloc(10);
// console.log(buffer);
// let buffer = Buffer.from("Hello everyone");
// console.log(buffer);
// let buffer = Buffer.from([0xe5,0xa4,0xa7,0xe5,0xae,0xb6,0xe5,0xa5,0xbd]);
// console.log(buffer.toString());

let buffer1 = Buffer.from([0xe5,0xa4,0xa7,0xe5]);
let buffer2 = Buffer.from([0xae,0xb6,0xe5,0xa5,0xbd]);
// // console.log(buffer1.toString());
// let newbuffer = Buffer.concat([buffer1,buffer2]);
// console.log(newbuffer.toString());

let { StringDecoder } = require("string_decoder");
let decoder =  new StringDecoder();
let res1 = decoder.write(buffer1);
let res2 = decoder.write(buffer2);
console.log(res1+res2);
// console.log(res2);

Stream stream

  • Stream: stream and data processing are inseparable
    • Principle of flow
    • Acquisition of stream data
      • pipe
      • data
      • end
    • Implementation of stream method of copy
    • Implementation of flow method of loading view
// stream;
const fs = require("fs");
// let res = fs.readFileSync("1.txt");
// console.log(res.toString());
let rs = fs.createReadStream("1.txt");//Component reading, read bit by bit to prevent warehouse explosion and insufficient memory;

let ws = fs.createWriteStream("2.txt");
rs.pipe(ws);//Write the data read in 1 into 2 and write it through pipe

 let num = 0;
 let str = "";
 rs.on("data",chunk=>{
     num++;
     str += chunk;
     // console.log(chunk);
     console.log(num);
 })
 // The flow is complete;
 rs.on("end",()=>{
   console.log(str);
 })
 
// 64kb data stream;

// Create a 65kb file;
// let buffer = Buffer.alloc(64*1024);
// fs.writeFile("65kb",buffer,err=>{
//     if(err){
//         return console.log(err);
//     }
//     console.log("write succeeded");
// })

Keywords: Javascript node.js Front-end

Added by smeagal on Thu, 17 Feb 2022 21:39:51 +0200