Home  >  Article  >  Web Front-end  >  Detailed introduction to modules and methods in nodejs

Detailed introduction to modules and methods in nodejs

不言
不言Original
2018-08-14 16:48:442134browse

This article brings you a detailed introduction to the modules and methods in nodejs. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Module loading specifications

Before ES6, js module loading solutions had appeared, the most important ones being CommonJS and AMD specifications. commonjs is mainly used in servers to achieve synchronous loading, such as nodejs. AMD specifications apply to browsers, such as requirejs, for asynchronous loading. There are also CMD specifications for synchronous loading solutions such as seaJS.

Nodejs has a simple module loading system. In Nodejs, files and modules have a one-to-one correspondence (each file is considered an independent module).

The only object that require can see is module.exports. It cannot see the exports object. The exports object we use when writing modules is actually just a reference to module.exports.

2, module.exports and exports

Every module in Nodejs will automatically create a module object. At the same time, there is an attribute called exports under the module object, which can export instances of a certain class. Assign to module.exports to export an instance of this class.

Before the module is executed, Nodejs will assign the value of module.exports to the global variable exports so that module.exports.f = ... can be written more concisely as exports.f = ... . Note: Like all variables, if exports is reassigned, it will no longer be bound to module.exports, and the specified module will not be exported

3. The mechanism of require

Assume Y is the path and X is the file name or directory name. When Nodejs encounters require(Y is a core module) and is loaded from memory between built-in modules

     a. Return to the module (for example: require("http")

     b. No longer continue execution

2. If Y starts with "./", "/" or "../" (relative paths and absolute paths are considered file modules)

        a. Treat X as a file and start from the specified path Start by searching for the following files: X, X.js, X.json, and Starting from the path, search for the following files in sequence: X/package.json (main field), X/index.js,

 3. A third-party module installed by npm, a package

If X is not a core module and does not start with "./", "/" or "../", then Nodejs It will start from the parent directory of the current module and try to load the module from its /node_module directory. If it is still not found, it will move to the next parent directory until the root directory of the file system

 4. Throw "not found"

4, the difference between import and require

​​ After the ES6 standard was released, module became the standard. The standard use is to export the interface with the export command (export this module to the outside) and introduce the module with import. However, in our usual node module, we adopt the CommonJS specification and use require to introduce the module. , use module.exports to export the interface.

ES6 implements module functions at the level of language specifications, and the implementation is quite simple. It can completely replace the existing CommonJS and AMD specifications and become a universal module solution for browsers and servers.

The syntax of import is different from require, and import must be placed at the beginning of the file, and no other logical code is allowed in front

import $ from 'jquery';
import * as _ from '_';
import {a,b,c} from './a';
import {default as alias, a as a_a, b, c} from './a';

​​ The use of require is very simple. It is equivalent to the portal of module.exports. What is the content behind module.exports? What is the result of require? Objects, numbers, strings, functions... and then assign the result of require to a certain Variables are equivalent to overlapping the positions of require and module.exports in parallel spaces. When using it, you can completely ignore the concept of modularity and use require. Just treat it as a node's built-in global function. Its parameters can even be expressions

require('./a')(); // a模块是一个函数,立即执行a模块函数
var data = require('./a').data; // a模块导出的是一个对象
var a = require('./a')[0]; // a模块导出的是一个数组

5, node asynchronous programming I/0 and events. Loop

The direct manifestation of Node.js asynchronous programming is callback. The callback function will be called after completing the task. Node uses a large number of callback functions. All Node APIs support callback functions.

We can read the file while executing other commands. After the file reading is completed, we return the file content as a parameter of the callback function. This way there is no blocking or waiting for file I/O operations while executing code. This greatly improves the performance of Node.js and can handle a large number of concurrent requests.

        Node.js 是单进程单线程应用程序,但是通过事件和回调支持并发,所以性能非常高。Node.js 的每一个 API 都是异步的,并作为一个独立线程运行,使用异步函数调用,并处理并发。

        Node.js 基本上所有的事件机制都是用设计模式中观察者模式实现。Node.js 单线程类似进入一个while(true)的事件循环,直到没有事件观察者退出,每个异步事件都生成一个事件观察者,如果有事件发生就调用该回调函数.

6,nodejs事件系统 Node.js EventEmitter

        Node.js 所有的异步 I/O 操作在完成时都会发送一个事件到事件队列。EventEmitter 对象如果在实例化时发生错误,会触发 error 事件。当添加新的监听器时,newListener 事件会触发,当监听器被移除时,removeListener 事件被触发。

// 引入 events 模块
var events = require('events');
// 创建 eventEmitter 对象
var eventEmitter = new events.EventEmitter();

方法:

       1,addListener(event, listener) 为指定事件添加一个监听器到监听器数组的尾部。

       2,on(event, listener) 为指定事件注册一个监听器,接受一个字符串 event 和一个回调函数。

       3,removeListener(event, listener) 移除指定事件的某个监听器,监听器必须是该事件已经注册过的监听器。它接受两个参数,第一个是事件名称,第二个是回调函数名称。

        4,removeAllListeners([event]) 移除所有事件的所有监听器, 如果指定事件,则移除指定事件的所有监听器

        5, listeners(event) 返回指定事件的监听器数组。

        6,emit(event, [arg1], [arg2], [...]) 按参数的顺序执行每个监听器,如果事件有注册监听返回 true,否则返回 false。

7,nodejs文件系统

        异步和同步:Node.js 文件系统(fs 模块)模块中的方法均有异步和同步版本,例如读取文件内容的函数有异步的 fs.readFile() 和同步的 fs.readFileSync()。异步的方法函数最后一个参数为回调函数,回调函数的第一个参数包含了错误信息(error)。

方法:

       1、打开文件 fs.open(path, flags[, mode], callback)

       2、获取文件信息 fs.stat(path, callback)

        3、写入文件 fs.writeFile(file, data[, options], callback)

        4、读取文件 fs.read(fd, buffer, offset, length, position, callback)

             参数使用说明如下:

                     fd - 通过 fs.open() 方法返回的文件描述符。

                     buffer - 数据写入的缓冲区。

                     offset - 缓冲区写入的写入偏移量。

                     length - 要从文件中读取的字节数。

                     position - 文件读取的起始位置,如果 position 的值为 null,则会从当前文件指针的位置读取。

                    callback - 回调函数,有三个参数err, bytesRead, buffer,err 为错误信息, bytesRead 表示读取的字节数,buffer 为缓冲区对象。

        5、关闭文件 fs.close(fd, callback)

        6、截取文件 fs.ftruncate(fd, len, callback)

        7、删除文件 fs.unlink(path, callback)

        8、创建目录 fs.mkdir(path[, mode], callback)

        9、读取目录 fs.readdir(path, callback)

        10、删除目录 fs.rmdir(path, callback)

8、Node.js Stream(流)

        Stream 是一个抽象接口,Node 中有很多对象实现了这个接口。例如,对http 服务器发起请求的request 对象就是一个 Stream,还有stdout(标准输出)。

        所有的 Stream 对象都是 EventEmitter 的实例。常用的事件有:

               data - 当有数据可读时触发。

               end - 没有更多的数据可读时触发。

               error - 在接收和写入过程中发生错误时触发。

Finish -All data has been triggered when it is written to the bottom system.

1. Create a readable stream

var readerStream = fs.createReadStream('input.txt');

2. Create a writable stream and write Go to the file output.txt

var writerStream = fs.createWriteStream('output.txt');

3. Pipeline read and write operations, read the contents of the input.txt file, and copy the contents Write to the output.txt file

readerStream.pipe(writerStream);

4. Compress the input.txt file to input.txt.gz, chain stream

fs.createReadStream('input.txt').pipe(zlib.createGzip()).pipe(fs.createWriteStream('input.txt.gz'));

5. Unzip input.txt.gz The file is input.txt

                                                                                                                                                                                                                                                                                           

9. Node.js global object

There is a special object in JavaScript called the global object (Global Object). It and all its properties can be used anywhere in the program. Local access, that is, global variables.

1. __filename __filename represents the file name of the script currently being executed. It will output the absolute path of the file location, and it may not be the same as the file name specified by the command line parameter. If in a module, the returned value is the path to the module file.

2. __dirname __dirname represents the directory where the currently executed script is located.

3. setTimeout(cb, ms) setTimeout(cb, ms) The global function executes the specified function (cb) after the specified number of milliseconds (ms). :setTimeout() only executes the specified function once. Returns a handle value representing the timer.

4. clearTimeout(t) clearTimeout(t) The global function is used to stop a timer previously created through setTimeout(). The parameter t is the timer created through the setTimeout() function.

5. setInterval(cb, ms) setInterval(cb, ms) The global function executes the specified function (cb) after the specified number of milliseconds (ms).

Returns a handle value representing the timer. The timer can be cleared using the clearInterval(t) function. The setInterval() method will continue to call the function until clearInterval() is called or the window is closed.

          6. Console console is used to provide console standard output. It is a debugging tool provided by the JScript engine of Internet Explorer, and later gradually became an implementation standard for browsers.

        7. Process process is a global variable, that is, a property of the global object. It is an object used to describe the current Node.js process status and provides a simple interface with the operating system. Important attributes include the standard input and output streams stdin and stdout

Related recommendations:

reacHow to implement the function of changing skin color

js Code to implement data transfer between pages

The above is the detailed content of Detailed introduction to modules and methods in nodejs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn