What are the core modules of node.js

What are the core modules of node.js

Global Object

In browser JS, window is usually the global object, while the global object in nodejs is global, and all global variables are properties of the global object.

Objects that can be directly accessed in nodejs are usually global properties, such as console, process, etc.

Global objects and global variables

The most fundamental role of global is to serve as a host for global variables.

Conditions for global variables:

Variables defined at the outermost level; properties of the global object; implicitly defined variables (variables that are not directly assigned values)

Defines a global variable which is also a property of the global object.

Always use var to define variables to avoid introducing global variables, because global variables pollute the namespace and increase the risk of code coupling.

process

process is a global variable, that is, a property of the global object. It is used to describe the state of the nodejs process object and provide a simple interface with the operating system.

process.argv is a command line parameter array. The first element is node, the second is the script file name, and from the third onwards each element is a running parameter.

console.log(process.argv);

process.stdout is the standard output stream.

process.stdin is the standard input stream.

The function of process.nextTick(callback) is to set a task for the event loop, and the callback will be called the next time the event loop responds.

There are also process.platform, process.pid, process.execPath, process.memoryUsage(), etc. POSIX process signal response mechanism.

console

Used to provide console standard output.

  • console.log()
  • console.error()
  • console.trace()

Common tools util

util is a Node.js core module that provides a collection of commonly used functions to make up for the shortcomings of the core js's overly streamlined functions.

util.inherits implements functions for prototype inheritance between objects. js object-oriented features are based on prototypes.

util.inspect method to convert any object to a string.

util.isArray(), util.isRegExp(), util.isDate(), util.isError(), util.format(), util.debug(), etc.

Event mechanism events--Events module

Events is the most important module of NodeJs. The architecture of NodeJs itself is event-based, and it provides a unique interface, so it can be called the cornerstone of NodeJs event programming.

Event Emitter

The events module only provides one object, events.EventEmitter. Its core is the encapsulation of event emission and event monitoring functions.

EventEmitter commonly used API:

  • EventEmitter.on(event, listener) registers a listener for the specified event, accepting a string event and a callback function listener.
  • EventEmitter.emit(event, [arg1], [arg2], [...]) emits the event event, passing several optional parameters to the event listener's parameter list.
  • EventEmitter.once(event, listener) registers a one-time listener for the specified event, that is, the listener will only be triggered once at most, and the listener will be released immediately after being triggered
  • EventEmitter.removeListener(event, listener) removes a listener for the specified event. The listener must be a listener that has been registered for the event.
  • EventEmitter.removeAllListeners([event]) removes all listeners for all events. If event is specified, all listeners for the specified event are removed.

error event

When an exception is encountered, an error event is usually emitted.

Inheriting EventEmitter

EventEmitter is not used directly, but inherited from the object. Including fs, net, http, as long as the core module supports event response is a subclass of EventEmitter.

File system fs--fs module

The encapsulation of file operations provides POSIX file system operations such as reading, writing, renaming, deleting, traversing directories, and linking files. There are two versions, asynchronous and synchronous.

fs.readFile(filename, [encoding], [callback(err, data)]) is the simplest function to read a file.

var fs = require("fs");
fs.readFile("server.js", "utf-8", function(err, data){
if (err){
    console.log(err);
}else{
    console.log(data);
}})

fs.readFileSync

fs.readFileSync(filename, [encoding]) is the synchronous version of fs.readFile. It accepts the same parameters as fs.readFile, and the read file content is returned as the function return value. If an error occurs, fs will throw an exception, which you need to capture and handle using try and catch.

fs.open

fs.read

Generally speaking, don't use the above two methods to read files unless necessary, because it requires you to manually manage buffers and file pointers, especially when you don't know the file size, which will be a very troublesome thing.

Http Module

The http module is mainly used to build http services, process user request information, etc.

Using http request

const http = require('http');
// Use to send http request const options = {
  protocol: 'http:',
  hostname: 'www.baidu.com',
  port: '80',
  method: 'GET',
  path: '/img/baidu_85beaf5496f291521eb75ba38eacbd87.svg'
};
let responseData = '';
const request = http.request(options, response => {
  console.log(response.statusCode); // Get the status code of the link request response.setEncoding('utf8');
  response.on('data', chunk => {
    responseData += chunk;
  });
  response.on('end', () => {
    console.log(responseData);
  });
});
request.on('error', error => {
  console.log(error);
});
request.end();

Creating a service using http

// Create a server using http const port = 3000;
const host = '127.0.0.1';
const server = http.createServer();
server.on('request', (request, response) => {
  response.writeHead(200, {
    'Content-Type': 'text/plain'
  });
  response.end('Hello World\n');
});
server.listen(port, host, () => {
  console.log(`Server running at http://${host}:${port}/`);
});

There are many more Node core modules, such as Buffer, crypto encryption, stream usage, net network, os operating system, etc.

The above is the detailed content of the node.js core modules. For more information about node.js core modules, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Modularity in Node.js, npm package manager explained
  • Detailed explanation of fs module and Path module methods in Node.js
  • Usage of Node.js http module
  • Talk about the module system in node.js
  • Detailed explanation of modularization in Node.js

<<:  Nginx content cache and common parameter configuration details

>>:  MySQL Basics in 1 Hour

Recommend

MySQL 8.0 WITH query details

Table of contents Learning about WITH queries in ...

3 common errors in reading MySQL Binlog logs

1. mysqlbinlog: [ERROR] unknown variable 'def...

Tutorial on using Docker Compose to build Confluence

This article uses the "Attribution 4.0 Inter...

CSS realizes div completely centered without setting height

Require The div under the body is vertically cent...

Example code and method of storing arrays in mysql

In many cases, arrays are often used when writing...

Use iframe to submit form without refreshing the page

So we introduce an embedding framework to solve th...

Summary of various forms of applying CSS styles in web pages

1. Inline style, placed in <body></body&g...

MySQL trigger principle and usage example analysis

This article uses examples to explain the princip...

Implementation of whack-a-mole game in JavaScript

This article shares the specific code for JavaScr...

Tutorial on installing Ubuntu 20.04 and NVIDIA drivers

Install Ubuntu 20.04 Install NVIDIA drivers Confi...

Detailed explanation of the usage of compose function and pipe function in JS

Table of contents compose function Array.prototyp...

How to completely delete the MySQL service (clean the registry)

Preface When installing the executable file of a ...

Vue implements two routing permission control methods

Table of contents Method 1: Routing meta informat...

Table related arrangement and Javascript operation table, tr, td

Table property settings that work well: Copy code ...

abbr mark and acronym mark

The <abbr> and <acronym> tags represen...