Preface:

Because I did not really learn Node.js before, but roughly learned the common commands of NPM and some modular syntax of Node.js, so I spent a day reading the Book “Node.js Development Guide” yesterday. This book helped me get a better picture of Node.js, but due to the early publication of the book, some oF the apis have been changed or deprecated, and the core is the most important part of learning Node.js. Therefore, I have summarized and combed the core of Chapter 4 -Node.js in coordination with the official documents of this book. Due to the limited level, please correct any omissions or mistakes.

The body of the

The core module is the heart of Node.js and is made up of streamlined libraries (much like Python in this respect) that provide the base API for Node.js. The main contents include:

Getting started with The Core of Node.js

  • Global object
  • Commonly used tools
  • Event mechanism

Getting started with The Core of Node.js

  • File system Access
  • HTTP server and client

Global object

In Node.js, the global object is changed to global, and all global variables (except global itself) are properties of the global object. The objects we can directly access in Node.js are usually global properties, such as console, process, etc.

Global objects and global variables

The most fundamental function of a global is to act as a host for global variables. According to the ECMAScript specification, variables that meet the following conditions are considered global variables:

  • Variables defined in the outermost layer (not in Node.js because node.js code executes in modules and does not define variables in the outermost layer)
  • Properties of a global object
  • Implicitly defined variables (that is, variables that are not defined and assigned directly)

When we define a global variable, the global variable automatically becomes a property of the global variable.

process

The Process object is a global variable that provides information about and controls the current Node.js process. It’s usually something we have to deal with when we’re writing native command line programs. Here are its most common member methods:

1.process.argv

The process.argv property returns an array containing the command line arguments that started the Node.js process. The first element is process.execPath, the second element is the path of the currently executing JavaScript file, and the remaining elements are other command line parameters.

For example, store a file named argv.js:

// print process.argv
process.argv.forEach((val, index) => {
  console.log(`${index}: ${val}`);
});

Copy the code

The command line runs like this:

$ node process-args.js one two=three four

0: /usr/local/bin/node
1: /Users/mjr/work/node/process-args.js
2: one
3: two=three
4: four
Copy the code

2.process.stdout

Process.stdout is the standard output stream, and normally we use console.log() to print characters, while the process.stdout.write() function provides a lower-level interface.

process.stdout.write('Please enter the value of num1:');
Copy the code

3.process.stdin

Process. stdin is the standard input stream, which is initially paused. To read data from the standard input, we must resume the stream and manually write its event response function.

Var num1, num2; /*2: output a message to the screen asking for num1*/ process.stdout.write('Please enter the value of num1:'); /*3: listen for user input */ process.stdin.on('data'.function (chunk) {
    if(! num1) { num1 = Number(chunk); /*4: input num2*/ process.stdout.write('Please enter the value of num2');
    } else {
        num2 = Number(chunk);
        process.stdout.write('Result:'+ (num1 + num2)); }});Copy the code

4.process.nextTick(callback[, …args])

. The process.nexttick () method, which args passes to callback when it calls it, adds callback to the “Next Tick queue”. Once the current event polling queue is complete, all callbacks in the Next Tick queue will be called in turn. This method is not an alias for setTimeout(fn, 0). It is more efficient, so don’t use setTimeout instead of process.nextTick. Event polling is followed by a call to ticks, which runs before any I/O events, including timers.

console.log('start');
process.nextTick(() => {
  console.log('nextTick callback');
});
console.log('scheduled');

// start
// scheduled
// nextTick callback
Copy the code

console

The console module provides a simple debugging console similar to the JavaScript console provided by Web browsers. This module exports two specific components:

  • A Console class containing methods such as console.log(), console.error(), and console.warn() can be used to write to any Node.js stream.
  • A global console instance that can be used to write to process.stdout and process.stderr. Global console is used without requiring require(‘console’). Note that the methods of the global Console object are neither always synchronous (as in similar apis in browsers) nor asynchronous (as in other Node.js streams).

For example, a common console instance globally:

console.log('hello, world'); // world console.log('hello%s'.'world');
// helloworld
console.error(new Error('Error message')); // Error: Error message const name ='description'; The console. Warn (` warning${name}`); Console.trace () // Outputs the current call stack to the standard error streamCopy the code

Common Console classes:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello, world'); // hello world myconsole.log ('hello%s'.'world');
// helloworld
myConsole.error(new Error('Error message')); // Error: Error message const name ='description'; MyConsole. Warn (` warning${name}`); // Warning descriptionCopy the code

Common tool util

The util module is used to support the internal API requirements of Node.js. Most of the utilities are also available to application and module developers to complement the functionality of the core JavaScript. It can be called like this:

const util = require('util');

Copy the code

1.util.inspect(object[, options])

The util.inspect() method returns a string representation of object, mainly for debugging and error output. Additional options can be used to change certain aspects of the formatted string. It takes at least one argument, objet, which is the argument to convert, and option, which is optional, as follows:

  • If showHidden is true, non-enumerable symbols and attributes of object are also included in the formatted result. The default is false.
  • Depth Specifies the number of recursion times when formatting an object. This is useful for viewing large, complex objects. The default value is 2. Null is passed to recurse indefinitely.
  • Colors If true, the output styles use ANSI color codes. The default value is false and can be customized.
  • If customInspect is false, the customInspect (depth, opts) function on object will not be called. The default is true.
  • If showProxy is true, Proxy objects and functions display their target and handler objects. The default is false.
  • MaxArrayLength specifies the maximum number of arrays and TypedArray elements that can be contained when formatted. The default is 100. Set to NULL to explicitly display all array elements. Set to 0 or negative, the array elements are not explicit.
  • BreakLength The length of an object’s key split into multiple lines. Infinity formats an object as a single line. The default value is 60.

For example, look at all the properties of the util object:

const util = require('util');
console.log(util.inspect(util, { showHidden: true, depth: null }));

Copy the code

2.util.callbackify(original)

The util.callbackify(original) method converts async asynchronous functions (or a function that returns a Promise value) into functions that follow the style of node.js callbacks. In the callback function, the first parameter err is the reason for the Promise Rejected (if the Promise state is Resolved, err is null), and the second parameter is the return value when the Promise state is Resolved. Such as:

const util = require('util');

async function fn() {
  return await Promise.resolve('hello world');
}
const callbackFunction = util.callbackify(fn);

callbackFunction((err, ret) => {
  if (err) throw err;
  console.log(ret);
});
// hello world
Copy the code

Note:

  • The callback function is executed asynchronously and has an exception stack error trace. If the callback throws an exception, the process will raise an ‘uncaughtException’ exception and exit if it is not caught.
  • Null has special meaning as an argument in the callback function. If the first argument to the callback function is the Promise Rejected argument with a return value, and the value can be converted to a Boolean value false, the value will be encapsulated in the Error object. This can be obtained by the attribute Reason.
function fn() {
  returnPromise.reject(null); } const callbackFunction = util.callbackify(fn); CallbackFunction ((err, ret) => {// When the Promise's rejecte is null, its Error and original values are stored in the'reason'In the. err && err.hasOwnProperty('reason') && err.reason === null;  // true
});
Copy the code

Event-driven events

Events is the most important module of Node.js, because node.js itself is event-based. Most Node.js core apis adopt the usual asynchronous event-driven architecture, and it provides a unique interface, so it can be called timely for Node.js event programming. The Events module is not only used by user code to interact with the node.js underlying event loop, but is also relied on by almost all modules.

All objects that can fire events are instances of the EventEmitter class. These objects expose an eventEmitter. On () function that allows one or more functions to be bound to named events that will be fired by the object. The event name is usually a humped string, but any valid JavaScript property name can be used. For each event, EventEmitter supports several event listeners. When an event is emitted, event listeners registered to the event are called in turn, and the event parameters are passed as callback function parameters.

Such as:

const EventEmitter = require('events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); // eventEmitter. On () is used to register listeners myEmitter. On ()'event', () => {
  console.log('Triggered an event! '); }); // the eventEmitter. Emit () method is used to emit the event myEmitter. Emit ('event');

Copy the code

Here’s a look at some of EventEmitter’s most commonly used apis:

  • The EventEmitter. On (event, Listener) method adds the listener function to the end of the listener array for an event named eventName. The listener is not checked to see if it has been added. Calling the same eventName and Listener multiple times causes the listener to be added and called multiple times.
  • The Emitter. PrependListener (eventName, Listener) method adds the listener function to the beginning of the listener array for an event named eventName. The listener is not checked to see if it has been added. Calling the same eventName and Listener multiple times causes the listener to be added and called multiple times.
  • The eventEmitter.emit() method allows you to pass arbitrary arguments to listener functions. When a normal listener function is called by EventEmitter, the standard this keyword is set to refer to the EventEmitter attached to the listener.
// Const myEE = new EventEmitter(); myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo'); // Print: // b // aCopy the code
  • EventEmitter. Once (event, listener) registers a single listener for a given event. That is, the listener is fired at most once.
server.once('connection', (stream) => {
  console.log('First call! ');
});
Copy the code
  • EventEmitter. RemoveListener (event listener) removes the specified event a listener, the listener must be the event listener has been registered. Note: removeListener removes at most one listener instance from the listener array. If any single listener is added more than once to the listener array specified for eventName, you must call removeListener multiple times to remove each instance.)
const callback = (stream) => {
  console.log('There's a connection! ');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);

Copy the code
  • EventEmitter. RemoveAllListeners ([event]) all removes all event listeners, if the event is specified, then remove all the specified event listeners
const callback = (stream) => {
  console.log('There's a connection! ');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
Copy the code

Error event

EventEmitter defines a special event called Error, which contains the semantics of “error” and is often emitted when we encounter anomalies. When an Error is emitted, EventEmitter states that if no listener is responding, Node.js will treat it as an exception, exit the program and print the call stack. We usually set up listeners for objects that emit error events, so that the whole program will not crash after encountering an error.

var events = require('events');
var emitter = new events.EventEmitter();
emitter.emit('error');
Copy the code

Inheritance EventEmitter

In most cases, EventEmitter will not be used directly, but will be inherited from objects. Any core module that supports event response, including FS and HTTP, is a subclass of EventEmitter. There are two reasons for this:

  • Object implementation events that have some entity function are semantically compliant, and the listening and firing of events should be methods of an object.
  • JavaScript object mechanism is prototype-based and supports partial multiple inheritance. Inheriting EventEmitter does not disturb the original inheritance relationship of objects.