SoFunction
Updated on 2025-03-10

What are the core modules

Global Object

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

Objects that can be accessed directly 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 of global variables.

Conditions for global variables:

Variables defined in the outermost layer; properties of global objects; implicitly defined variables (variables with direct assignments are not defined)

Define a global variable, which is also a property of a global object.

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

process

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

It is an array of command line parameters, the first element is node, the second is the script file name, and each element is a running parameter starting from the third.

();

is the standard output stream.

is a standard input stream.

The function of (callback) is to set a task for the event loop, which will call callback the next time the event loop calls the response.

There are also, , , () etc. Posix process signal response mechanism.

console

Used to provide console standard output.

  • ()
  • ()
  • ()

Common tools util

util is a core module that provides a collection of commonly used functions to make up for the shortcomings of the over-simplified functionality of core js.

Functions that implement prototype inheritance between objects. The js object-oriented feature is based on prototypes.

A method to convert any object into a string.

(), (), (), (), (), ()wait

Event mechanism events--Events module

events are the most important modules of NodeJs. NodeJs' architecture itself is event-based, and it provides the only interface, so it can be regarded as the cornerstone of NodeJs event programming.

Event transmitter

The events module only provides one object. Its core is the encapsulation of event transmission and event monitor functions.

Common APIs for EventEmitter:

  • (event, listener) Register a listener for the specified event, accepting a string event and a callback function listener.
  • (event, [arg1], [arg2], [...]) Emit event, passing several optional parameters to the parameter table of the event listener.
  • (event, listener) Register a single listener for a specified event, that is, the listener will only fire once at most, and the listening will be immediately released after the trigger.
  • (event, listener) Removes a listener for the specified event. The listener must be the listener that the event has registered.
  • ([event]) Remove all listeners for all events, and if an event is specified, remove all listeners for the specified event.

error event

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

Inherit EventEmitter

Instead of using EventEmitter directly, it is inherited in the object. Including fs, net, and http, as long as the core module that 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 links. There are two versions: asynchronous and synchronous.

(filename, [encoding], [callback(err, data)]) is the simplest function to read files.

var fs = require("fs");
("", "utf-8", function(err, data){
if (err){
    (err);
}else{
    (data);
}})

(filename, [encoding]) is a synchronized version. It accepts the same parameters, and the read file content will be returned as the function return value. If an error occurs, fs will throw an exception, you need to use try and catch to catch and handle the exception.

Generally speaking, do not 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 can be a cumbersome thing.

Http module

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

Use http request

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

Create a service using http

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

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

The above is the detailed content of what core modules are available. For more information about core modules, please pay attention to my other related articles!