Home >Web Front-end >JS Tutorial >Node Learning Chat Module System

Node Learning Chat Module System

青灯夜游
青灯夜游forward
2023-01-30 20:10:222420browse

This article will talk about the module system in Node.js, including events module, util module, fs module, OS module, Path module, etc. I hope it will be helpful to you!

Node Learning Chat Module System

Module System

Reference: Node.js Module System

In order to allow Node.js files to call each other, Node.js provides a simple module system.
Modules are the basic components of Node.js applications, and files and modules have a one-to-one correspondence.
In other words, a Node.js file is a module. This file may be JavaScript code, JSON, or a compiled C/C extension.

There are 4 types of modules in Node.js (native modules and 3 types of file modules)
Example: var http = require("http");

Node.js comes with a module called http. We request it in our code and assign the return value to a local variable.
This turns our local variable into an object with all the public methods provided by the http module. [Related tutorial recommendations: nodejs video tutorial]

Load module:

  • Load from the file module cache
  • From native Module loading
  • Loading from file
    • require method accepts the following parameters:
      • http, fs, path, events, util, etc., native modules.
      • ./mod or.../mod, file module with relative path.
      • /pathtomodule/mod, file module with absolute path.
      • mod, file module of non-native module.

Module interface

  • exports The object is the interface exposed by the module
  • require The object is used to obtain the interface of a module from the outside, that is, the exports object of the obtained module.
//例子
//hello.js
exports.world = function() {       //相当于给function()函数取了个别名world()
    console.log('Hello World');
  }

//main.js
var hello = require('./hello');
hello.world();  //访问 hello.js 的 world 函数

//结果
PS E:\learn> node main.js
Hello World
  • Just want to encapsulate an object into a module: module.exports = function() {...}
    The only change in the module interface is Use module.exports = Hello instead of exports.world = function(){}. When the module is referenced externally, its interface object is the Hello object itself to be output, not the original exports.

Use of exports and module.exports
If you want to expose properties or methods to the outside world, just use exports. To expose objects (similar to class, including Many properties and methods), just use module.exports.

//hello.js 
function Hello() { 
    var name; 
    this.setName = function(thyName) { 
        name = thyName; 
    }; 
    this.sayHello = function() { 
        console.log('Hello ' + name); 
    }; 
}; 
module.exports = Hello;   

//main.js 
var Hello = require('./hello'); 
hello = new Hello(); 
hello.setName('BYVoid'); 
hello.sayHello();

//结果
PS E:\learn> node main.js
Hello BYVoid

events module

Reference: Node.js EventEmitter

The events module only provides one object: events.EventEmitter. The core of EventEmitter is the encapsulation of event triggering and event listener functions.

  • events is a module, use require("events"); to access the module.
  • EventEmitter is equivalent to the only class in the events module. There are multiple attributes under this class
    • addListener(event, listener) Adds a listener for the specified event to the end of the listener array.
    • on(event, listener) The on function registers a listener for the specified event and accepts a string event and a callback function.
    • once(event, listener) Register 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 triggering
    • removeListener(event, listener)Remove a listener for the specified event. The listener must be a registered listener for the event. It accepts two parameters, the first is the event name, the second is the callback function name
    • removeAllListeners([event]) Removes all listeners for all events, if the event is specified , removes all listeners for the specified event.
    • setMaxListeners(n) By default, EventEmitters will output a warning message if you add more than 10 listeners. The setMaxListeners function is used to change the default limit number of listeners.
    • listeners(event) Returns the listener array for the specified event.
    • emit(event, [arg1], [arg2], [...]) Execute each listener in the order of the listeners. If the event has a registered listener, return true. Otherwise return false.
    • listenerCount(emitter, event) Returns the number of listeners for the specified event.
//例子
//event.js 文件
var events = require('events');            // 引入 events 模块
var emitter = new events.EventEmitter();   // 创建 eventEmitter 对象
//为事件someEvent注册两个监视器
emitter.on('someEvent', function(arg1, arg2) { 
    console.log('listener1', arg1, arg2); 
}); 
emitter.on('someEvent', function(arg1, arg2) { 
    console.log('listener2', arg1, arg2); 
}); 
//按顺序执行someEvent的每个监视器
emitter.emit('someEvent', 'arg1 参数', 'arg2 参数');  // 'arg1 参数', 'arg2 参数'为参数arg1,arg2的值
//结果
$ node event.js 
listener1 arg1 参数 arg2 参数
listener2 arg1 参数 arg2 参数

util module

References:
util Utility Tools Official Website
Node.js Common Tools

util 是一个Node.js 核心模块,提供常用函数的集合,用于弥补核心 JavaScript 的功能 过于精简的不足。

util.callbackify(original)
将 async 异步函数(或者一个返回值为 Promise 的函数)转换成遵循异常优先的回调风格的函数

  • 参数:original 为 async 异步函数。
  • 返回值:返回传统回调函数(或者一个返回值为 Promise 的函数)
    • 在返回的回调函数中,第一个参数为拒绝的原因(如果 Promise 解决,则为 null),第二个参数则是解决的值。
//例子
const util = require('util');

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

callbackFunction((err, ret) => {
  if (err) throw err;
  console.log(ret);
});

//结果
hello world

util.inherits(constructor, superConstructor) 是一个实现对象间原型继承的函数。

//例子
var util = require('util'); 
//Base构造函数内三个属性
function Base() {    
    this.name = 'base'; 
    this.base = 1991; 
    this.sayHello = function() { 
    console.log('Hello ' + this.name); 
    }; 
} 

//原型中定义的一个函数
Base.prototype.showName = function() { 
    console.log(this.name);
}; 

//Sub构造函数内一个属性
function Sub() { 
    this.name = 'sub'; 
} 

util.inherits(Sub, Base);  //Sub从Base继承
var objBase = new Base(); 
objBase.showName(); 
objBase.sayHello(); 
console.log(objBase); 

var objSub = new Sub(); 
objSub.showName(); 
//objSub.sayHello(); 
console.log(objSub); 

//结果
base 
Hello base 
{ name: 'base', base: 1991, sayHello: [Function] } 
sub 
{ name: 'sub' }
//Base 有 name , base , sayHello() , showName()
//Sub  有 name(自己定义的,不是继承的) , showName() 从Base继承的
  • util.inspect(object,[showHidden],[depth],[colors]) 是一个将任意对象转换 为字符串的方法,通常用于调试和错误输出。它至少接受一个参数 object,即要转换的对象。
    • 它至少接受一个参数 object,即要转换的对象。
    • showHidden 是一个可选参数,如果值为 true,将会输出更多隐藏信息。
    • depth 表示最大递归的层数,如果对象很复杂,你可以指定层数以控制输出信息的多 少。如果不指定depth,默认会递归 2 层,指定为 null 表示将不限递归层数完整遍历对象。
    • 如果 colors 值为 true,输出格式将会以 ANSI 颜色编码,通常用于在终端显示更漂亮 的效果。
var util = require('util'); 
function Person() { 
    this.name = 'byvoid'; 
    this.toString = function() { 
    return this.name; 
    }; 
} 
var obj = new Person(); 
console.log(obj);
console.log(util.inspect(obj)); 
console.log(util.inspect(obj, true));

Node Learning Chat Module System

fs 模块

参考资料:Node.js 文件系统
Node.js 文件系统模块 官网
fs.open(path, flags[, mode], callback) 在异步模式下打开文件

  • 参数:

    • path - 文件的路径。
    • flags - 文件打开的行为。具体值详见下文。
    • mode - 设置文件模式(权限),文件创建默认权限为 0666(可读,可写)。
    • callback - 回调函数,带有两个参数如:callback(err, fd)

    r 以读取模式打开文件。如果文件不存在抛出异常。
    r+ 以读写模式打开文件。如果文件不存在抛出异常。
    rs 以同步的方式读取文件。
    rs+ 以同步的方式读取和写入文件。
    w 以写入模式打开文件,如果文件不存在则创建。
    wx 类似 ‘w’,但是如果文件路径存在,则文件写入失败。
    w+ 以读写模式打开文件,如果文件不存在则创建。
    wx+ 类似 ‘w+’, 但是如果文件路径存在,则文件读写失败。
    a 以追加模式打开文件,如果文件不存在则创建。
    ax 类似 ‘a’, 但是如果文件路径存在,则文件追加失败。
    a+ 以读取追加模式打开文件,如果文件不存在则创建。
    ax+ 类似 ‘a+’, 但是如果文件路径存在,则文件读取追加失败。

fs.stat(path, callback) 通过异步模式获取文件信息

  • 参数:
    • path - 文件路径。
    • callback - 回调函数,带有两个参数如:callback(err, stats), stats 是 fs.Stats 对象。

fs.stat(path)执行后,会将stats类的实例返回给其回调函数。可以通过stats类中的提供方法判断文件的相关属性

stats.isFile() 如果是文件返回 true,否则返回 false。
stats.isDirectory() 如果是目录返回 true,否则返回 false。
stats.isBlockDevice() 如果是块设备返回 true,否则返回 false。
stats.isCharacterDevice() 如果是字符设备返回 true,否则返回 false。
stats.isSymbolicLink() 如果是软链接返回 true,否则返回 false。
stats.isFIFO() 如果是FIFO,返回true,否则返回 false。FIFO是UNIX中的一种特殊类型的命令管道。
stats.isSocket() 如果是 Socket 返回 true,否则返回 false。

fs.writeFile(file, data[, options], callback) 异步模式下写入文件
writeFile 直接打开文件默认是 w 模式,所以如果文件存在,该方法写入的内容会覆盖旧的文件内容。

  • Parameters:
    • file - file name or file descriptor.
    • data - The data to be written to the file, which can be a String or Buffer object.
    • options - This parameter is an object containing {encoding, mode, flag}. The default encoding is utf8, the mode is 0666, and the flag is 'w'
    • callback - callback function. The callback function only contains error information parameters (err) and returns
    ## when writing fails.

#fs.read(fd, buffer, offset, length, position, callback) Read the file in asynchronous mode. This method uses the file descriptor to read the file.

    Parameters:
    • fd - the file descriptor returned by the fs.open() method.
    • buffer - The buffer to which data is written.
    • offset - The write offset for buffer writes.
    • length - The number of bytes to read from the file.
    • position - The starting position for file reading. If the value of position is null, it will be read from the position of the current file pointer.
    • callback - callback function with three parameters err, bytesRead, and buffer. err is the error message, bytesRead represents the number of bytes read, and buffer is the buffer object.

fs.close(fd, callback) Close the file in asynchronous mode. This method uses the file descriptor to read the file.

    Parameters:
    • fd - the file descriptor returned by the fs.open() method.
    • callback - callback function, no parameters.

fs.ftruncate(fd, len, callback) Intercept the file in asynchronous mode. This method uses the file descriptor to read the file.

    Parameters:
    • fd - the file descriptor returned by the fs.open() method.
    • len - The length of the truncated file content.
    • callback - callback function, no parameters.

fs.unlink(path, callback) Syntax format for deleting files:

    Parameters:
    • path - file path.
    • callback - callback function, no parameters.

fs.mkdir(path[, options], callback) Create directory

    Parameters:
    • path - file path
    • options parameters can be
      • recursive - whether to create directories recursively, the default is false.
      • mode - Set directory permissions, default is 0777.
    • callback - callback function, no parameters.

fs.readdir(path, callback) Read directory

    Parameters:
    • path - File path
    • callback - callback function, the callback function takes two parameters err, files, err is the error message, files is the file array list in the directory

fs.rmdir(path, callback) Delete directory

    Parameters:
    • path - file path
    • callback - callback function , no parameters.

OS module

Reference:

Node.js OS module Properties:
os.EOL Constants that define the end-of-line character of the operating system. Method:

os.tmpdir() Returns the default temporary folder of the operating system
os.endianness() Returns the endianness of the CPU, possible is "BE" or "LE".
os.hostname() Returns the host name of the operating system.
os.type() Returns the operating system name
os.platform() Returns the compiled operating system name
os.arch() Returns the operating system CPU architecture, possible values ​​are "x64", "arm" and "ia32".
os.release() Returns the release version of the operating system.
os.uptime() Returns the time the operating system has been running, in seconds.
os.loadavg() Returns an array containing 1, 5, and 15 minute load averages.
os.totalmem() Returns the total amount of system memory in bytes.
os.freemem() Returns the amount of free memory in the operating system, in bytes.
os.cpus() Returns an object array containing information about each installed CPU/core: model, speed (unit MHz), time (one contains user, nice, sys, idle and irq object of CPU/core milliseconds used).
os.networkInterfaces() Get the list of network interfaces.

Path module

Node.js Path module

Net module

Node.js Net module

DNS module

Node.js DNS module

Domain module

Node.js Domain module

http module

Reference material:Node,js Web module

url module

gulp module

ES6 environment setup

Webpack module

Webpack introductory tutorial

For more node-related knowledge, please visit: nodejs tutorial !

The above is the detailed content of Node Learning Chat Module System. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete