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

Why can't my tomcat start?

Table of contents Phenomenon: Port usage: Spellin...

Solve the problem of docker pull image error

describe: Install VM under Windows 10, run Docker...

Summary of B-tree index knowledge points in MySQL optimization

Why do we need to optimize SQL? Obviously, when w...

How to create scheduled tasks using crond tool in Linux

Preface Crond is a scheduled execution tool under...

Example of implementing GitHub's third-party authorization method in Vue

Table of contents Creating OAuth Apps Get the cod...

JavaScript to implement the web version of the snake game

This article shares the specific code for JavaScr...

Nodejs implements intranet penetration service

Table of contents 1. Proxy in LAN 2. Intranet pen...

How to start multiple MySQL instances in CentOS 7.0 (mysql-5.7.21)

Configuration Instructions Linux system: CentOS-7...

Attributes in vue v-for loop object

Table of contents 1. Values ​​within loop objects...

How to use selenium+testng to realize web automation in docker

Preface After a long time of reading various mate...

Detailed explanation of react setState

Table of contents Is setState synchronous or asyn...

js to achieve simulated shopping mall case

Friends who are learning HTML, CSS and JS front-e...