Node.js Core Introduction (1)

  • Global object
  • Commonly used tools
  • Event mechanism

Getting started with The Core of Node.js

  • File system Access
  • HTTP server and client

File system FS

Fs module is the encapsulation of file operation, it provides file read, write, rename, delete, traverse directory, link and other POSIX file system operations, and all methods have asynchronous and synchronous form. The last argument to an asynchronous method is a callback function. The arguments passed to the callback function depend on the method, but the first argument of the callback function is always reserved for the exception. If the operation completes successfully, the first argument will be null or undefined.

const fs = require('fs');
fs.unlink('/tmp/hello', (err) => {
  if (err) throw err;
  console.log('Delete/TMP /hello successfully');
});

Copy the code

When using the synchronous method, any exceptions are thrown immediately. You can use try/catch to handle exceptions, or bubble them up.

const fs = require('fs');
fs.unlinkSync('/tmp/hello');
console.log('Delete/TMP /hello successfully');

Copy the code

1.fs.readFile(path,[options], callback)

Fs.readfile (path,[options], callback) is the simplest read. It takes a mandatory argument named filename, which indicates the filename to read. The second argument, options, is optional and represents the character encoding of the file. Callback is a callback function that receives the contents of a file. If options are not specified, callback is the second argument. The callback function provides two parameters, err and data. Err indicates whether an error occurred, and data is the file content. If options are specified, data is a parsed string; otherwise, data is binary data represented as a Buffer. Such as:

fs.readFile('/etc/passwd'.'utf8', callback);
Copy the code

Note that the behavior of fs.readfile () and fs.readfilesync () is platform-dependent when path is a directory. On macOS, Linux, and Windows, an error is returned. On FreeBSD, a representation of the contents of the directory is returned.

// On macOS, Linux, and Windows: fs.readfile ('<directory>', (err, data) => {
  // => [Error: EISDIR: illegal operation on a directory, read <directory>]
});

//  在 FreeBSD 上:
fs.readFile('<directory>', (err, data) => {
  // => null, <data>
});
Copy the code

2.fs.readFileSync(path[, options])

Fs. readFileSync(filename,[encoding]) is the version of fs.readFile synchronization. It takes the same arguments as fs.readfile, but the contents of the readFile are returned as values from the function. If an error occurs, FS will throw an exception, and we need to use try and catch to catch and handle the exception.

3.fs.open(path, flags[, mode], callback)

Fs. open(path, flags[, mode], callback) is a package of POSIX open functions, similar to the C standard library fopen function. It takes two mandatory arguments, path is the file path, and flags can be the following values:

'r' - Opens the file in read mode. An exception occurs if the file does not exist. 'r+' - Opens files in read/write mode. An exception occurs if the file does not exist. 'RS +' - Opens files in synchronous read/write mode. Command the operating system to bypass the local file system cache. (This is useful for opening files in NFS mount mode, as it lets you skip potentially old local caches. It has a significant impact on I/O performance, so do not use this flag unless necessary. Note that this does not cause fs.open() to enter a synchronous blocking call. If that's what you want, you should use fs.opensync (). 'w' - Opens the file in write mode. The file will be created (if it doesn't exist) or truncated (if it does). 'wx' - similar to 'w', but fails if path exists. 'W +' - Opens files in read/write mode. The file will be created (if it doesn't exist) or truncated (if it does). 'wx+' - similar to 'w+', but fails if path exists. 'A' - Opens the file in append mode. If the file does not exist, it will be created. 'ax' - similar to 'a', but fails if path exists. 'A +' - Opens the file in read and append mode. If the file does not exist, it will be created. 'ax+' - similar to 'a+', but fails if path exists.Copy the code

Mode Specifies the file mode (permission and sticky bits), but is valid only when a file is created. The default value is 0O666, which can be read and written.

4.fs.read(fd, buffer, offset, length, position, callback)

Fs. read(fd, buffer, offset, Length, position, callback) encapsulates POSIX read functions and provides a lower-level interface than fs.readFile. Reads data from the file specified by fd. A buffer is the buffer to which data will be written. Offset is the offset at which the buffer starts writing. Length is an integer that specifies the number of bytes to read. Position specifies the position from which to start reading in the file. If position is null, data is read from the current file read location, and the file read location is updated. If position is an integer, the file read position remains the same. The callback takes three arguments (err, bytesRead, buffer).

var fs = require('fs');
fs.open('content.txt'.'r'.function(err, fd) {
if (err) {
console.error(err);
return;
}
var buf = new Buffer(8);
fs.read(fd, buf, 0, 8, null, function(err, bytesRead, buffer) {
if (err) {
console.error(err);
return;
}
console.log('bytesRead: '+ bytesRead); console.log(buffer); })});Copy the code

Output:

bytesRead: 8
<Buffer 54 65 78 74 20 e6 96 87>
Copy the code

HTTP server and client

The Node.js standard library provides HTTP modules that encapsulate an efficient HTTP server and a simple HTTP client. HTTP.Server is an event-based HTTP Server. Its core is realized by the C++ part of node.js, and the interface is encapsulated by JavaScript, which gives consideration to high performance and simplicity. Http. request is an HTTP client tool for making requests to the HTTP server, such as Pingback or content fetching.

The HTTP interface in Node.js is designed to support many features of the protocol. For example, chunk encoded messages. These interfaces do not buffer complete requests or responses, and the user can process the data as a stream. The HTTP header is represented by an object where the key name is lowercase and cannot be modified:

{ 'content-length': '123'.'content-type': 'text/plain'.'connection': 'keep-alive'.'host': 'mysite.com'.'accept': '* / *' }
Copy the code

In order to support a wide range of POSSIBLE HTTP applications, node.js’s HTTP API is very low-level. It involves only flow processing and message parsing. It parses a message into headers and bodies, but does not parse a specific header or body. The key name is lowercase and cannot be changed. In order to support a wide range of POSSIBLE HTTP applications, node.js’s HTTP API is very low-level. It involves only flow processing and message parsing. It parses a message into headers and bodies, but does not parse a specific header or body.

The HTTP server

HTTP.Server is an HTTP Server object in HTTP module. All systems based on HTTP protocol made with Node.js, such as websites, social applications and even proxy servers, are realized based on HTTP. It provides a very low level of encapsulation API, just flow control and simple learning parsing, and all the advanced functionality is implemented through its interface. Take this example from the official website:

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type'.'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/ `); })Copy the code

In this code, http.createserver ([requestListener]) is used to create a new instance of http.server. Let’s look at http.createserver ([requestListener]) for now.

1. Http. Server events

HTTP.Server is an event-based HTTP Server. All requests are encapsulated as independent events, and developers only need to write response functions to its events to achieve all functions of the HTTP Server. It is derived from EventEmitter and provides the following events:

  • Request: Triggered each time a request is received. Note that there may be multiple requests per connection (in the case of HTTP keep-alive connections).
  • Connection: Triggered when a new TCP stream is created. Socket is an object of type net. socket. Typically, users do not need to access this event. Note that because of the way the protocol parser is bound to the socket, the socket will not emit the ‘readable’ event. Socket can also be accessed through request.connection.
  • Connect: Triggered whenever the client sends an HTTP Connect request. If the event is not listened for, the client sending the CONNECT request closes the connection. When the event is triggered, there is no ‘data’ event listener on the requested socket, which means that a’ data’ event listener needs to be bound to handle data sent from the socket to the server.
  • Close: This event is triggered when the server is shut down. Note that not when the user is disconnected, but when the server is down.

The most commonly used of these events is request is the most commonly used, so HTTP provides a shortcut: Http.createserver ([requestListener]), which creates an HTTP server and uses requestListener as a listener for request events. This is the case in the example above, which is explicitly implemented like this:

//httpserver.js
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = new http.Server();
server.on('request', (req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type'.'text/plain');
  res.end('Hello World\n');
});
server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/ `); })Copy the code

2. http.ServerRequest

HTTP.ServerRequest is HTTP request information, which is the most important thing for backend developers. It is usually sent by the HTTP. Server’s request event, passed as the first parameter, commonly referred to as the request or HTTP request is generally divided into two parts: the request Header and the request Body. All of the above contents are short in length and can be read immediately after the request header is parsed. The request body may be relatively long and require a certain amount of time to transfer, so http.ServerRequest provides the following three events to control the transfer of the request body. The req. HTTP requests are generally divided into two parts: the RequestHeader (RequestHeader) and the request body (RequsetBody). All of the above contents are short in length and can be read immediately after the request header is parsed. The request body may be relatively long and require a certain amount of time to transfer, so http.ServerRequest provides the following three events to control the transfer of the request body. Http. ServerRequest provides three events to control the transfer of the request body:

  1. Data: When the request body data arrives, this event is fired, providing a parameter to the callback function, is the received data, this event may be called multiple times (all data in order, is the request body data). If the event is not listened for, the request body is discarded.

  2. End: This event is emitted when the request body data completes. No more data events are emitted thereafter;

  3. Close: This event is triggered when the user’s current request ends. Unlike end, close is still called if the user forces the transfer to be terminated.

    Table 4-2 Attributes of the ServerRequest Name Meaning Complete Whether the client request is sent. HttpVersion HTTP version, usually 1.0 or 1.1 method HTTP request method. For example, the original url request path of GET, POST, PUT, and DELETE. For example, /static/image/x. JPG or /user? Name =byvoid headers HTTP Request header (uncommon) Connection Current HTTP connection socket, Socket instance Socket connection attribute alias Client Client attribute aliasCopy the code

3. Obtain the content of the GET request

Note that none of the properties provided by HTTP. ServerRequest are similar to those in the PHP languageThe GET request is embedded directly in the path. The URL is the complete request path (including? The following section), so manually parse what follows as the parameters of the GET request. The parse function in the URL module of Node.js provides this functionality.

To the url: http://127.0.0.1/user? For example: name=byvoid&[email protected]

var http = require("http");
var url = require("url");
var server = new http.Server();
server.on("request".function (req, res) {
    if (req.url == "/favicon.ico") {
        return;
    }
    var m = url.parse(req.url, true);
    console.log(m)
    res.writeHead(200, {'Content-type': 'text/html; charset = utf8'});
    res.end();
})
server.listen(80);
console.log("The server begin");
Copy the code

Console. log output:

Url {
  protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search:'? name=byvoid&[email protected]',
  query: { name: 'byvoid', email:'[email protected]' },
  pathname: '/user',
  path:'/user? name=byvoid&[email protected]',
  href:'/user? name=byvoid&[email protected]' 
}
Copy the code

4. Obtain the content of the POST request

Version 1.1 of the HTTP protocol provides eight standard request methods, the most common of which are GET and POST. Whereas a GET request encodes all content into the access path, a POST request has all content in the request body. HTTP.ServerRequest does not have any property content in the request body, because waiting for the request body to transfer can be a time-consuming task, such as uploading a file. Most of the time, the content of the request body may be ignored, and a malicious POST request can consume a lot of server resources. So node.js doesn’t parse the request body by default, so when we need it, we write it by hand. Here’s how:

var http = require('http');
var querystring = require('querystring');
var util = require('util');
http.createServer(function(req, res) {
    var post = ' ';
    req.on('data'.function(chunk) {
    post += chunk;
});
req.on('end'.function() {
    post = querystring.parse(post);
    res.end(util.inspect(post));
    });
}).listen(3000);
Copy the code

5.http.ServerResponse

Http. ServerResponse is the information returned to the client that determines what the user ultimately sees. It is also sent by http.Server’s request event, passed as the second parameter, and is commonly referred to simply as Response or RES. ServerResponse has three important member functions that return the response header, the response content, and terminate the request:

  • Response.writehead (statusCode, [headers]) : Sends a response header to the requesting client. StatusCode is an HTTP statusCode, such as 200 (request succeeded) or 404 (not found). Headers is an associative array-like object that represents each attribute of the response header. This function can only be called once in a request, and if it is not called, a response header is automatically generated.
  • Response.write (data, [encoding]) : sends a response to the requesting client. Data is a Buffer, or string, that represents what is to be sent. If data is a string, you need to specify encoding to specify its encoding, which is UTF-8 by default. Response.write can be called multiple times before response.end is called.
  • Response.end ([data], [encoding]) : ends the response to inform the client that all sending is complete. This function must be called once all the content to be returned has been sent. It takes two optional arguments that have the same meaning as Response.write. If this function is not called, the client is in a waiting state forever.

The HTTP client

The HTTP module provides two functions, http.request and http.get, to make requests to the HTTP server as a client.

1.http.request(options,callback)

Http. request(options,callback) Initiates an HTTP request. It takes two parameters. Option is an associative array-like object representing the parameters of the request, and callback is the callback function of the request. The common parameters of option are as follows:

  • Host: indicates the domain name or IP address of the requested website.
  • Port: the port used to request the website. The default value is 80.
  • Method: Request method. The default is GET.
  • Path: The requested path relative to the root. The default path is /. QueryString should be included. For example, / search? Query = byvoid.
  • Headers: An associative array object that is the content of the request header.

Callback, in turn, passes an instance of http.ClientResponse. Http. request returns an instance of http.ClientRequest, and here is the code for sending a POST request via http.request:

var http = require('http');
var querystring = require('querystring');
var contents = querystring.stringify({
    name: 'byvoid',
    email: '[email protected]',
    address: 'Zijing 2#, Tsinghua University'}); var options = { host:'www.byvoid.com',
    path: '/application/node/post.php',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'.'Content-Length' : contents.length
    }
};
var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data'.function (data) {
    console.log(data);
    });
});
req.write(contents);
req.end();
Copy the code

The running results are as follows:

array(3) {
["name"]=>
string(6) "byvoid"
["email"]=>
string(17) "[email protected]"
["address"]=>
string(30) "Zijing 2#, Tsinghua University"
}
Copy the code

2.http.get(options, callback)

The HTTP module also provides a simpler way to handle GET requests: http.get(options, callback). It is a simplified version of http.request, the only difference being that http.get automatically sets the request method to get and does not require a manual call to req.end() :

var http = require('http');
http.get({host: 'www.byvoid.com'}, function(res) {
    res.setEncoding('utf8');
    res.on('data'.function (data) {
    console.log(data);
    });
});
Copy the code

http.ClientRequest

This object is created and returned within http.request(). It represents a request that is being processed, and its request header has been queued. It provides a response event, which is the binding object of the callback function specified by the second parameter of http.request or http.get.

var http = require('http');
var req = http.get({host: 'www.byvoid.com'});
    req.on('response'.function(res) {
    res.setEncoding('utf8');
    res.on('data'.function (data) {
    console.log(data);
    });
});
Copy the code

Http. ClientRequest, like http.ServerResponse, also provides write and end functions to send the request body to the server, usually for POST, PUT, and so on. The end function must be called to notify the server when all writes are complete, otherwise the request is invalid. ClientRequest also provides the following common functions:

  • Request.abort () : Flags the request to abort. Calling this method causes the remaining data in the response to be discarded and the socket destroyed.
  • Request. setTimeout(timeout,[callback]) : Sets the request timeout time. Timeout is milliseconds. Socket.settimeout () is called once the socket has been assigned to the request and is connected.
  • Request. end([data[, encoding]][, callback]) ends sending the request. If part of the request body has not yet been sent, they are flushed to the stream. If the request is chunked, the terminating character ‘0\r\n\r\n’ is sent.

http.ClientResponse

Similar to HTTP. ServerRequest, http.ClientResponse provides three events, data, End, and Close, which are triggered when data arrives, transfer ends, and connection ends respectively. The Data event passes a parameter, chunk, which represents the received data.

ClientResponse also provides attributes to indicate the result status of the request:

StatusCode HTTP statusCode, such as 200, 404, or 500. HttpVersion HTTP version. This is usually 1.0 or 1.1.Copy the code

ClientResponse also provides the following special functions:

  • Responsetencoding ([encoding]) : Sets the default encoding. When the data event is triggered, the data will be encoded in encoding. The default value is NULL, which is not encoded and stored as a Buffer. The common encoding is UTF8.
  • Response.pause () : suspends receiving data and sending events to facilitate downloading.
  • Response.resume () : Resumes from the paused state.