The HTTP module

Cross domain: cross domain in the way of proxy, for example, I have a front end, a background, Xiaoming has a background. My front-end needs to access Xiaoming’s backend, which is called cross-domain, but if I use my own backend to access Xiaoming’s backend using HTTP request, there is no need for cross-domain, so I can use my front-end to access my own backend using Ajax to complete data requests. ,

Create server: Post to data via Ajax

// Load http.js in the library, load into the variable HTTP, which is an object
var reg = require("http");
// Req is the data that the client requests from the server
//res sends data to the server item client
Reg.createserver Creates a service
var server = reg.createServer(function (req, res) {
    var data = "";
//req.on("data") is an event in which the data requested by the client is being received
    req.on("data".function (d) {
        data += d;
    });
//req.on("end") indicates that the data requested by the client is received
    req.on("end".function () {
        var obj = JSON.parse(data);
// header file, with * at the end indicating that all domains are allowed access
        res.writeHead(200, {
            "Content-Type": "text/plain"."Access-Control-Allow-Origin": "*"
        });
        res.write(JSON.stringify(obj));
        res.end();
    });
});
// Listen for events
server.listen(1024."localhost".function () {
    console.log("Registration service started, listening started.");
});
Copy the code

Crawler get data:

// Introduce the HTTP module
const http = require('http');
// Initiate short requests from the server
const fs = require('fs');
http.get('http://localhost/test/1.html'.(res) = > {
    const {
        statusCode
    } = res;/ / status code
    const contentType = res.headers['content-type'];// The type of request
    let error;
    if(statusCode ! = =200) {
        error = new Error('Status code error');
    }
    if (error) {
        console.log(error.message);
        res.resume();// Clear the request cache
        return;
    }
// Data processing
    res.setEncoding('utf8');// Set the encoding format of the data
    let data = ' ';
    res.on('data'.function (d) {
        data += d;// Receive segmented information
    });
    res.on('end'.() = > {
        // console.log(data);
// Write to local file after receiving
        fs.writeFile('./test1.html', data, 'utf8'.(err) = > {
            if (err) {
                throw err
            }
            console.log('Download completed'); })}); }).on('error'.(e) = > {
    console.error(`Got error: ${e.message}`);// Error message returned
});
Copy the code

URL module

Const url = require(‘url’);

let urlstring='http://www.baidu.com:8080/home/login/test?name=wy&ps=wanger#hash'
const myURL = url.parse(urlstring,true);
// Parse converts url strings into URL-formatted objects
Copy the code
 let obj={
	protocol: 'http:'.slashes: true.auth: null.host: 'www.baidu.com:8080'.port: '8080'.hostname: 'www.baidu.com'.hash: '#hash'.search: '? name=wy&ps=wanger'.query: { name: 'wy'.ps: 'wanger' },
	pathname: '/home/login/test'.path: '/home/login/test? name=wy&ps=wanger'.href:'http://www.baidu.com:8080/home/login/test?name=wy&ps=wanger#hash' 
}
let result=url.format(obj)
//format Changes the URL object to a CHARACTER in the URL format
Copy the code

The QueryString module

Let qs=require(‘ queryString ‘);

parse(query,"%".The '@')// Convert a string to an object
qs.stringify(obj,The '@'."!")// Convert an object to a character
qs.escape(query)// Encode Chinese characters or special characters in query
qs.unescape(code)// Decode Chinese characters or special characters in query
Copy the code

The Path module

Const path=require(‘path’);

path.join()// Implement path stitching
path.join(__dirname,'./file.js')//__dirname is the folder of the current file, which can be concatenated, separated by commas:
path.join(__dirname,'.. / '.'./hw'.'mail.js')
path.basename('path')// The current file name
path.dirname('path')// Name of the current folder
path.extname('path')/ / extension
Copy the code

The Events module

Const Event = require(‘events’);

Start with the following code (unlike the other modules)

class MyEmitter extends Event {}

// Class inheritance

const myEmitter = new MyEmitter();

// Instantiate object new object

// Add object listener

let callback=(food,food2) = >{

    console.log('eat'+food+food2);

}
Copy the code

Then, the happy call

myEmitter.on('eat',callback);//eat is the event name
myEmitter.emit('eat'.'aaaaa'.'bbbb')// The parameter can be passed
myEmitter.removeAllListeners()// Remove all events
myEmitter.removeListener('eat',callback);// Remove an event
Copy the code

The Stream flow

Const fs=require(‘fs’);

let read=fs.createReadStream('./events.js')// Create a readable stream
let  write=fs.createWriteStream('./events3.js')// Create writable streams
Copy the code

An example of reading a Stream and copying a picture

const fs = require('fs');
let read = fs.createReadStream('./file/test1.png');// Create a new readable Stream file
let data = ' ';// The external container loads the data
read.setEncoding('binary');// Convert to image format, default utf8
read.on('data'.(d) = >{
    data+=d;// Stream data each time
});
read.on('end'.() = >{
    fs.writeFileSync('./file/test2.png',data,'binary');// Write data to a file
});
Copy the code

 

An example of reading a Stream and copying a picture as a writable Stream

const fs = require('fs');
let read = fs.createReadStream('./file/test1.png');// Create a new readable Stream file
let change = fs.createWriteStream('./file/test3.png'.'binary');// Create a writable Stream file
read.setEncoding('binary');// Convert format (image)
read.on('data'.(d) = >{
    change.write(d);// Stream storage, no need to wait until the data is loaded
});
Copy the code

Read plus write completes replication with PIPE

// Achieve streaming copy of files
const fs=require('fs')
let read = fs.createReadStream('./file/test1.png'.'binary'); // Create a new readable Stream file
let change = fs.createWriteStream('./file/test4.png'.'binary'); // Create a writable Stream file
read.pipe(change);// Transfer the readable stream to the writable stream file
Copy the code

Zlib module

Const zip = require(‘zlib’); and

const fs = require(‘fs’);

const gzip = zip.createGzip();// Create a new file compression
let input = fs.ReadStream('./test1.png');// The file passed in
let output = fs.WriteStream('./test1.gzip');// Generate the compressed file
input.pipe(gzip).pipe(output);//pipe
Copy the code