The core module

Global objects and global variables

  • In the Node environment, the global object is global. In the browser environment, the global object is window
  • All global variables are mounted on the global object as properties of the global object and contain:
    • Explicitly defines the properties of a global object
    • Implicitly defined variables (variables for which no direct assignment is defined)
    • It is recommended to define variables using var, let, and const to avoid introducing global variables, which pollute the namespace and increase the coupling risk of your code.

Commonly used global variables

Process: An object that describes the current node.js process state and provides a simple interface to the operating system

  • Argv is an array of command line arguments. The first element is node, the second element is the script file name, and each element is a run argument starting with the third element
  • Process.nexttick (callback) puts the callback into an asynchronous Micro Task queue so that if the callback takes a long time to execute, it does not block the main thread console: Console standard output
  • Console.log () is a normal output, or you can print console.log(‘%d year’, 1993) using placeholders like the C printf() command.
  • Console. error() outputs an error
  • Console.trace () prints the current call stack

Event-driven events module

EventEmitter and Listeners: Events. EventEmitter objects

  • EventEmitter. On (event, Listener) registers a listener for the specified event, taking a string event and a callback function listener
  • EventEmitter.emit(event, [arg1], [arg2], […] Emits the event event, passing several optional parameters to the parameter table of the event listener
  • EventEmitter. Once (event, listener) registers a single listener for a given event. That is, the listener is fired at most once
  • EventEmitter. RemoveListener (event listener) removes the specified event a listener, the listener must be the event listener has been registered
  • EventEmitter. RemoveAllListeners ([event]) all removes all event listeners, if the event is specified, then remove all the specified event listeners
      var events = require('events');
      var emitter = new events.EventEmitter();
      emitter.on('event'.function(arg1, arg2) { console.log('listener1', arg1, arg2);
      });
      emitter.on('event'.function(arg1, arg2) { console.log('listener2', arg1, arg2);
      });
      emitter.emit('someEvent'.'hello'.'world');
      // listener1 hello world
      // listener2 hello world
    Copy the code

Most of the time we don’t use EventEmitter directly, but instead inherit it from objects. Core modules supporting event responses, including FS, NET, and HTTP, are subclasses of EventEmitter. Instances of modules can listen for events using the on() method

File system FS module

  • Fs.readfile () reads file contents asynchronously
  • Fs.readfilesync () reads file contents synchronously
  • Fs.open () opens the file
  • Fs.read () reads the file (reading data from the specified file descriptor fd and writing to the buffer object pointed to by buffer), using fs.read() in its callback function after fs.open() first opens the file. In general, don’t read files this way unless you have to, because it requires you to manually manage buffers and Pointers to files, which can be cumbersome especially if you don’t know the file size.
      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); })});// bytesRead: 8
      // <Buffer 54 65 78 74 20 e6 96 87>
    Copy the code

The HTTP module

The HTTP module encapsulates an HTTP server and HTTP client

HTTP Server (implemented based on http.server objects)

Http.createserver () creates an http.server instance object

var http = require('http');
http.createServer(function(req, res) { 
    res.writeHead(200, {'Content-Type': 'text/html'}); 
    res.write('<h1>Node.js</h1>');
    res.end('<p>Hello World</p>');
}).listen(3000);
console.log("HTTP server is listening at port 3000.");
Copy the code

The two parameters in the http.createServer callback function, req and res, are instances of http.ServerRequest and http.ServerResponse, respectively, representing request and response information

HTTP.ServerRequest is HTTP request information, all business logic is based on the content of the request to expand, so it is the most concerned content of back-end developers

Contains some common attributes:

  • Data: This event is emitted when the request body data arrives. The event provides a parameter, chunk, to represent the received data. If the event is not listened for, the request body is discarded. The event may be called multiple times
  • End: This event is triggered when the request body data transfer is complete, after which no more data will arrive
  • Close: This event is triggered when the user’s current request ends
GET the CONTENT of the GET request: Use url.parse to parse the parameters following the URL in the GET request
var http = require('http'); 
var url = require('url'); 
var util = require('util');
http.createServer(function(req, res) { 
    res.writeHead(200, {'Content-Type': 'text/plain'}); 
    res.end(util.inspect(url.parse(req.url, true))); // util.inspect is a utility function that converts an object to a string
}).listen(3000);
Copy the code
Gets the POST request content

The body of the POST request is collected using the data event of http.ServerRequest, and the content of the POST request is parsed using QueryString.parse

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

Don’t use this simple method to fetch POST requests in a real production application because it has serious efficiency issues and security issues, but this is just an example to help you understand.

Http. ServerResponse is the information returned to the client that determines what the user ultimately sees

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 be called at most once within 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

HTTP client (making requests to the server as a client)

  • Http. request(options, callback) Initiates an HTTP request
    • Option is an associative array-like object that represents the parameters of the request, and callback is the callback function of the request
    • Callback passes a parameter, an instance of http.ClientResponse
    • Http. request returns an instance of http.ClientRequest
      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(); // Don't forget to end the request with req.end(), otherwise the server will not receive the message
    Copy the code
  • Http.get (options, callback) is a simplified version of the get request. The only difference is that http.get automatically sets the request method to get and does not require a manual call to req.end().
ClientRequest object (instance object returned by http.request())

The object contains methods:

  • The write() server sends the request body
  • End () must be called to notify the server after the write is complete, otherwise the request is invalid
Http.clientresponse object (the instance object is the parameter in the http.request() callback)

Provides three events:

  • Data Data reach is triggered
  • End Triggered when data transmission ends
  • Close Triggered after the connection ends

Three 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