Home > Article > Web Front-end > Node Learning Chat Module System
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!
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:
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
module.exports = function() {...}
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
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 triggeringremoveListener(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 参数
References:
util Utility Tools Official Website
Node.js Common Tools
util 是一个Node.js 核心模块,提供常用函数的集合,用于弥补核心 JavaScript 的功能 过于精简的不足。
util.callbackify(original)
将 async 异步函数(或者一个返回值为 Promise 的函数)转换成遵循异常优先的回调风格的函数
//例子 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,即要转换的对象。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.js 文件系统
Node.js 文件系统模块 官网fs.open(path, flags[, mode], callback)
在异步模式下打开文件
参数:
callback(err, fd)
r
以读取模式打开文件。如果文件不存在抛出异常。r+
以读写模式打开文件。如果文件不存在抛出异常。rs
以同步的方式读取文件。rs+
以同步的方式读取和写入文件。w
以写入模式打开文件,如果文件不存在则创建。wx
类似 ‘w’,但是如果文件路径存在,则文件写入失败。w+
以读写模式打开文件,如果文件不存在则创建。wx+
类似 ‘w+’, 但是如果文件路径存在,则文件读写失败。a
以追加模式打开文件,如果文件不存在则创建。ax
类似 ‘a’, 但是如果文件路径存在,则文件追加失败。a+
以读取追加模式打开文件,如果文件不存在则创建。ax+
类似 ‘a+’, 但是如果文件路径存在,则文件读取追加失败。
fs.stat(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 模式,所以如果文件存在,该方法写入的内容会覆盖旧的文件内容。
#fs.read(fd, buffer, offset, length, position, callback) Read the file in asynchronous mode. This method uses the file descriptor to read the file.
fs.close(fd, callback) Close the file in asynchronous mode. This method uses the file descriptor to read the file.
fs.ftruncate(fd, len, callback) Intercept the file in asynchronous mode. This method uses the file descriptor to read the file.
fs.unlink(path, callback) Syntax format for deleting files:
fs.mkdir(path[, options], callback) Create directory
fs.readdir(path, callback) Read directory
fs.rmdir(path, callback) Delete directory
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.
Reference material:Node,js Web module
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!