How to use Node.js

quote
https://www.bilibili.com/video/BV1QT4y1A7NR?p=1
https://www.bilibili.com/video/BV17z4y1D7Yj?p=520&spm_id_from=pageDriver

1, Understanding Node.js

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.
Node.js is an open source and cross platform JavaScript runtime environment running on the server side. It can parse JS code without the restriction of browser security level, and provides many system level API s.
In short, Node.js is JavaScript running on the server side

  1. File read / write File System
  2. Process management process
  3. Network communication HTTP/HTTPS

2, Install Nodejs

1. Install NVM nodejs version management tool

Use nvm URL
http://nvm.uihtm.com/

If there is a node before and nvm is not installed, uninstall the original nodejs first, and then install nvm.

2.nvm command

View installable versions
nvm list  available

Install the specified version node
nvm install Version number

Select the to use after installation node edition
nvm use Version number

node function js file
node file name


3.nvm FAQs

1. Slow download

If Download node Too slow, please replace the domestic image source, stay nvm Under the installation path of, find settings.txt,set up node_mirro And npm_mirror Is the domestic image address. The download is fast~~

root: D:\nvm
path: D:\nodejs
node_mirror: https://npm.taobao.org/mirrors/node/
npm_mirror: https://npm.taobao.org/mirrors/npm/

2.nvm installation node access denied

Use the nvm use version number to check the access denied by node -v. note that the installation path must be installed under D: / and the nvm and nodejs paths must be under D disk.

3.nvm runs node, reports an error, and exit s Chinese garbled code

An error is reported after upgrading the nvm version. 1.1.7 upgrade 1.1.8

Run cmd with administrator.
Or uninstall with version 1.1.7

4. Install nodemon - real time detection file

cnpm install nodemon -g

-g Global installation

Startup file:
nodemon file name

5. Install Taobao image cnpm

cnpm is domestic

npm install -g cnpm --registry=https://registry.npmmirror.com

-g Global installation

3, Nodejs module

nodejs needs to follow the CommonJs specification to use custom modules
.

1. Use built-in module

When viewing the API on the official website, you can directly reference the corresponding built-in module

const os =require("os");

console.log(os.hostname());

2. Use third-party modules

First initialize the folder npm init, generate the package.json file, install the third-party module, and import the module.

initialization npm
npm  init 

load package.json Package under file
npm install    / npm i

3. Use custom module

A js file is a module. First define the module and then reference the module.

Note: when calling the custom module, add. / to the reference path to tell the system that it refers to the local, and it should also be added at the current level. Without, the system will first find the built-in module, then the third party, and then the user-defined module, which will save time.


4, Module use

1.fs - file read / write

. / means local, can write or not

const fs =require("fs");

fs.writeFile("./log.txt","fs File reading and writing",(err,data) =>{
    if(err){

    }else{
        console.log("File written successfully")
    }
})

2.process - process operation

console.log(process.argv);

3.http - Communication Protocol

You can create a server through node

const http=require("http");

const server= http.createServer((request,response) =>{
    let url= request.url
    response.write(url)
    response.end()
    
});

server.listen(8090,"localhost",()=>{
    console.log("localhost:8090")
})

5, npm usage

1.npm version number and command

The version number symbol in package.json is npm management version number

npm Clean cache
npm cache clean --force


2. Create your own package concurrent version to npm


publish your own package

3. Change the source of npm

Changing to Taobao is equivalent to installing cnpm.

6, npm script

The npm script is written under scripts in the package.json file

Run npm script command

npm run Custom script name

1. Operation documents

One & When symbols run two files at the same time, they run in parallel. It is possible that 1 runs first and 2 runs first
"runjs":"node ./xxx1.js & node ./xxx2.js" 

Two & The symbol is serial. The previous file is executed first, and then the subsequent file is executed
"runjs":"node ./xxx1.js && node ./xxx2.js"

2. Short commands start and test

    "start": "node ./xxx.js",
    "test": "echo \"Error: no test specified\" && exit 1",

Run these two short commands without adding run
npm start
npm test

3.npm view package.json custom content

To view the attribute contents of the package.json file, you need a fixed prefix process.env.npm_package_ Followed by the object and property you want to view

console.log(process.env.npm_package_config_age);

be careful:
To view the contents of the package.json file and run the viewed js file, you must run it with scripts. To access variables in the script environment

4. Install github or gitee package for NPM

5. Cross env cross platform tool


6.nrm manages the download source of npm

7.npx

Role of npx:
1. If there is a package installed locally, the local package will be called instead of global installation
2. If it is not available locally, it will be installed in a virtual environment and deleted after one use, which will not occupy memory.


7, Built in module

log4js log package

npm install log4js -D

to configure

const log4js = require("log4js");
log4js.configure({
  appenders: { cheese: { type: "file", filename: "cheese.log" } },
  categories: { default: { appenders: ["cheese"], level: "error" } }
});
 
const logger = log4js.getLogger("cheese");
logger.trace("Entering cheese testing");
logger.debug("Got cheese.");
logger.info("Cheese is Comté.");
logger.warn("Cheese is quite smelly.");
logger.error("Cheese is too ripe!");
logger.fatal("Cheese was breeding ground for listeria.");

1.url

const url=require("url");
const log4js = require("log4js");

// const logger = log4js.getLogger();

log4js.configure({
    appenders: { cheese: { type: "file", filename: "cheese.log" } },
    categories: { default: { appenders: ["cheese"], level: "error" } }
  });
  const logger = log4js.getLogger("cheese");
  logger.level = "debug";
logger.debug("Some debug messages");
const urlString="https://www.baidu.com:445/path/index.xml?id=2#tag=3"

const urlObj={
    protocol: 'https:',
    slashes: true,
    auth: null,
    host: 'www.baidu.com:445',
    port: '445',
    hostname: 'www.baidu.com',
    hash: '#tag=3',
    search: '?id=2',
    query: 'id=2',
    pathname: '/path/index.xml',
    path: '/path/index.xml?id=2',
    href: 'https://www.baidu.com:445/path/index.xml?id=2#tag=3'
  }

// logger.debug(url.parse(urlString)); 
logger.debug(url.format(urlObj))
logger.debug(url.resolve("https://www.baidu.com/a","/b"))


2.querystring query string

The querystring module provides utilities for parsing and formatting URL query strings

. stringify is used to format strings

querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });
// Returns 'foo=bar&baz=qux&baz=quux&corge='

querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':');
// Returns 'foo:bar;baz:qux'

The querystring.unescape(str) method performs decoding of URL percentage encoded characters on a given str

3.http



Pull the interface in the back through get

-https.request(options,()=>{})

https.request(options,(result)=>{})
The first parameter is options, which is the request parameter. The second parameter is the return value, which can be operated by the arrow function.

The request method will return a request that needs to be received

request can do get, post, etc


-http response

response.writeHead(statusCode[, statusMessage][, headers])

Send a response header to the request. The status code is a 3-bit HTTP status code, such as 404. The last parameter headers is the response header. Optionally, a human readable statusMessage is given as the second parameter.

headers can be arrays, where keys and values are in the same list. It is not a tuple list. Therefore, even offsets are key values and odd offsets are associated values. The format of this Array is the same as request.rawHeaders.

Returns a reference to ServerResponse so that it can be called chained.

response.writeHead(200, {
    'Content-Length': Buffer.byteLength(body),
    'Content-Type': 'text/plain'
  })

response.end([data[, encoding]][, callback])
This method sends a signal to the server to indicate that all response headers and text have been sent; The server should consider this message complete. The response.end() method must be called on each response.

5. Cross domain jsonp

Cross domain: the browser's request for js, jpg and other files of other domain names will not trigger the homology policy. If the interface is requested through ajax, the same origin policy is triggered

6. Cross domain cors


const http = require('http')
const url = require('url')
const server= http.createServer((request,response)=>{
    let urlStr=request.url
    let urlObj=url.parse(urlStr,true)

    switch (urlObj.pathname) {
        case '/api/data':
            response.writeHead(200,{
                'content-type':'applicatio/json',
                'Access-Control-Allow-Origin': '*'
            })
            response.write('{"ret":"true","data":"hellp"}')
            break;
    
        default:
            response.write('page not find')
            break;
    }
    response.end()
})

server.listen(8080,()=>{
    console.log('localhost:8080')
})

7. Cross domain - access other people's port through proxy HTTP proxy Middleware

const http =require('http');
const url=require('url')
const {createProxyMiddleware}=require('http-proxy-middleware')
const server= http.createServer((request,response)=>{
   const urlStr =request.url
    if(/\/ajax_new/.test(urlStr)){
        // console.log(urlStr)
        const proxy= createProxyMiddleware('/ajax_new',{
            target:'http://www.jumeiglobal.com',
            changeOrigin:true
        })
        proxy(request,response)
    }else{
        console.log('error')
    }
})

server.listen(8080,()=>{
    console.log('localhost:8080')
})

8.events

Events custom events
If the event can have the same name, it will be triggered twice

//Call the events module and return a class
const EventEmitter= require("events") 

//Write a class to inherit the returned class
class MyEventEmitter extends EventEmitter{

}

//instantiation 
const event =new MyEventEmitter()
//Bind the event through on, customize a method named play, and obtain the value through the callback function
event.on('play',(value)=>{
    console.log(value)
})

//Using play events with the emit method
event.emit('play','history');

9.fs file operation

async: asynchronous
Sync: sync
Some methods are followed by these two words, indicating that this method can be synchronous and asynchronous






//Call fs module to read and write files
const fs =require("fs");

//Create a folder using mkdir. The first parameter is the file name, and the second parameter is the callback function, which can pass in error: err
fs.mkdir('logs',(err)=>{
    if(err) throw err
    console.log('Folder created successfully')
})

//Use fs.rename to modify the file name, fs.rename(oldPath, newPath, callback)
fs.rename('./logs','./log',()=>{
    console.log('File name modified successfully')
})

//Use fs.rmdir(path[, options], callback) to delete the folder,
 fs.rmdir('./log',()=>{
    console.log('done')
})
//Use fs.readdir(path[, options], callback) to read the file directory
fs.readdir('./log',(err,result)=>{
    console.log(result)
})

//Use fs.appendFile(path, data[, options], callback)
//Append data to a file asynchronously and create the file if it does not already exist. Data can be a string or < buffer >.
fs.appendFile('./log/log.txt',',Add text after!!!',()=>{
    console.log('Added successfully');
})

//Use fs.readFile(path[, options], callback). The second parameter is optional: if the character format is not set, the buffer is read. Or toString()
fs.readFile('./log/log.txt',"utf-8",(err,content)=>{
    console.log(content);
})
fs.readFile('./log/log.txt',(err,content)=>{
    console.log(content.toString());
})

-fs/promise asynchronous API

Promise: promise

fs/promise API, which returns the asynchronous operation of promise

//Use fs/promises to asynchronously operate the file and return promise
;(async ()=>{
    let result = await fsPromises.readFile('./log/log.txt')
    console.log(result.toString())
})()

-Loop read directory

//Loop create file
// for(var i=0;i<=6;i++){
//     fs.writeFile(`./log/log-${i}.txt `, ` the ${i} log file `, () = >{
//         console.log("done.")
//     })
// }

//Read files in directory
function readDir(dir){
    fs.readdir(dir,(err,content)=>{
        //Loop through files
        content.forEach((value,index)=>{
            let joinDir=`${dir}/${value}`;
            fs.stat(joinDir,(err,stats)=>{
                if(stats.isDirectory()){
                    readDir(joinDir)
                }else{
                    fs.readFile(joinDir,'utf-8',(err,content)=>{
                        console.log(content)
                    })
                }
            })
        })
    })
}

readDir('./');

-fs.watch listens to a file

//Observation file fs.watch
fs.watch('./log/log-0.txt',(err)=>{
    console.log('file has changed')
})


-zlib compression, read stream and write stream

// Introduce the required package
const fs = require('fs')
const zlib = require('zlib')
const gzip = zlib.createGzip()

//Create stream
const readStream = fs.createReadStream('./log.txt')
const writeStream = fs.createWriteStream('./log2.txt')

//Copy file
readStream  //Get content
    .pipe(gzip) //Use compression
    .pipe(writeStream) //write file

-readLine read line by line

Input function

//Introduction module
const readline=require('readline')

//Create read interface
const rl =readline.createInterface({
    input:process.stdin,
    output:process.stdout
})

//input
rl.question('Input content',(answer)=>{
    console.log(`What you entered is:${answer}`)
    rl.close()
})

10.crypto encryption

const crypto =require('crypto')

const password='abc123'
const hash= crypto
    .createHash('sha1') //Define the encryption algorithm to get the hash
    .update(password)   //Define encryption object, optional character format
    .digest('hex')  //  Cryptosystem

console.log(hash)

11. Routing

What is routing:
Node.js router provides a one-to-one mapping mechanism from URL request path to node.js method
Intercept the path from the front end through request, and use request to get the data from the front end. If you want to send data to the front end, send it to the front end through response

const fs =require('fs')
const mime = require('mime')
//http.createServer create service
require('http').createServer((request,response)=>{
    //Get request path
    const urlString =request.url
    console.log(urlString)
    //Get the suffix of the path through mime and write it to the request header
    const type=mime.getType(urlString.split('.')[1])
    response.writeHead(200,{
        'content-type':type
    })
    //Read the file according to the entered path, and pay attention to the file path filled in
    const file= fs.readFileSync(`.${urlString}`)
    //Input read file
    response.end(file)
   
    // switch (urlString) {
    //     case '/':
    //         response.end('hello')
    //         break
    //     case '/home':
    //         fs.readFile('./home.html',(err,content)=>{
    //             response.end(content)
    //         })
    //         break
    //     case '/app.js':
    //         fs.readFile('./app.js',(err,content)=>{
    //             response.end(content)
    //         })
    //         break
    //     case '/color_bg_3.jpeg':
    //         fs.readFile('./color_bg_3.jpeg',(err,content)=>{
    //             response.end(content)
    //         })
    //         break;
    //     default:
    //         console.log('page of 404')
    //         break
    // }
}).listen(8080,()=>{
    console.log('localhost:8080')
})

12. Static resource directory

13.path

-path.jion()

Purpose: splice directory path

path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
// Return: '/ foo/bar/baz/asdf'

-path.parse()

Resolve the path and return the path object

path.parse('/home/user/dir/file.txt');
// return:
// { root: '/',
//   dir: '/home/user/dir',
//   base: 'file.txt',
//   ext: '.txt',
//   name: 'file' }

*Practice static resource directory

server.js

const http = require('http')
const path = require('path')
const readStaticFile = require('./readStaticFile');


http.createServer(async (req, res) => {
    let urlString = req.url
    const filePath = path.join(__dirname, '/public', urlString)
    console.log(filePath);
    let { mimeType, data } = await readStaticFile(filePath)
    console.log(mimeType)
    res.writeHead(200, {
        'content-type': `${mimeType};charset=utf-8`
    })
    res.write(data)
    res.end()
}).listen(8080, () => console.log('localhost:8080'))


readStaticFile.js

const path = require('path')
const mime = require('mime')
const fs = require('fs')
//Read the file according to the obtained path
function readGetFile(file) {
    return new Promise((resolve, reject) => {
        fs.readFile(file, (err, data) => {
            if (err) {
                resolve('You are returning a folder without index.html file')
            } else {
                resolve(data)
            }
        })
    })
}

//Read file return stream
async function readStaticFile(filePathName) {
    let ext = path.parse(filePathName).ext
    let mimeType = mime.getType(ext) || 'text/html'
    let data
    //Determine whether the file exists
    if (fs.existsSync(filePathName)) {

        //Determine whether it is a folder or a file
        if (ext) {
            //    readGetFile(filePathName)
            //    .then(result=> data=result)
            //    .catch(err => data=err)
            data = await readGetFile(filePathName)
        } else {
            // readGetFile(path.join(filePathName,'/index.html'))
            // .then(result=> data=result)
            // .catch(err => data=err)
            data = await readGetFile(path.join(filePathName, '/index.html'))
        }

    } else {
        data = 'file not found'
    }

    return {
        mimeType,
        data
    }
}

//Throw method
module.exports = readStaticFile

8, Third party module

1.mime

mime.getType() gets the suffix of the file to get the content type
mime.getExtension gets the file name suffix through content type

mime.getType('txt');                    // ⇨ 'text/plain'
mime.getExtension('text/plain');        // ⇨ 'txt'

9, yarn

Yarn is a package manager and can also be used as a project management tool.
To install yarn, you need to install nodejs first



Tags: node.js Front-end

Posted on Wed, 01 Dec 2021 08:55:14 -0500 by Wade