Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the common built-in modules in Node.js

2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article focuses on "what are the common built-in modules in Node.js". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what are the common built-in modules in Node.js.

Built-in module path

The drill of the path

The path module is used to process paths and files and provides many useful methods.

And we know that the path delimiters on Mac OS, Linux, and windows are different.

Use / as the file path delimiter on the Unix operating system of Mac OS and Linux

``or\ is used as the delimiter of the file path on windows, and / is currently supported.

So what if we develop an application on windows using\ as a delimiter, what should we do to deploy to Linux?

There will be some problems with the display path

So in order to shield the differences between them, we can use the path module for the operation of paths in development.

If we blindly concatenate two paths, such as path2 +'/'+ path3, it may be possible to run in the current operating system, but if we change the operating system to execute code, we may not recognize the path, because different operating systems require different path separators.

Const path = require ('path') / / our path2 and path3 deliberately write the wrong separator const path2 =' User\ ASUS\ DCC'const path3 = 'MyWork\ May 4' / / the resolve method in the path object can realize the splicing of the correct path separator between the two paths according to the current operating system const fileName = path.resolve (path2, path3) / / you can see that our original string was originally concatenated with\ After passing the path.resolve method, it is changed to use\ to splice console.log (fileName). / / C:\ Users\ ASUS\ Desktop\ Front-end Learning\ algorithm\ User\ ASUS\ DCC\ MyWork\ May 4

Other methods of path module

1. Get information about the path

The path.dirname () method returns the directory name of a path

The path.basename () method returns the last part of a path, which is generally the file name.

The path.extname () method returns the extension of path

Const path = require ('path') const file =' / foo/bar/baz/asdf/quux.html'const path2 = path.dirname (file) const path3 = path.basename (file) const path4 = path.extname (file) console.log (path2); / / foo/bar/baz/asdfconsole.log (path3); / / quux.htmlconsole.log (path4); / / .html

2. Join path stitching

The path.join () method concatenates all given path fragments together using platform-specific delimiters and normalizes the generated path. To put it simply, it is according to the current operating system to select the appropriate path separator to join multiple paths together, of course, it will also correct the incorrect delimiters in the original path.

Const path = require ('path') const path2 =' / USER/ASUS'const path3 = 'My/DCC'const fileName = path.join (path2, path3) console.log (fileName); / /\ USER\ ASUS\ My\ DCC

3. Resolve method stitching (most used)

The path.resolve () method parses the sequence of a path or path fragment into an absolute path.

Const path = require ('path') const path2 =' asd/sad'const path3 = 'My/DCC'const fileName1 = path.join (path2, path3) const fileName2 = path.resolve (path2, path3) console.log (fileName1); / / asd\ sad\ My\ DCCconsole.log (fileName2); / / C:\ Users\ ASUS\ Desktop\ Front-end Learning\ algorithm\ asd\ sad\ My\ DCC

4. The difference between resolve and join methods

If an absolute path is not generated after processing all the given path fragments, the current working directory is used and it recognizes.. /,. / and /

Path.resolve ('wwwroot',' static_files/png/','.. / gif/image.gif'); / / return'/ home/myself/node/wwwroot/static_files/gif/image.gif' if the current working directory is / home/myself/node,//

The given sequence of paths is processed from right to left, and each path is parsed in turn until an absolute path is constructed.

Const path = require ('path') const path2 =' asd/sad'const path3 ='/ My/DCC'const fileName1 = path.join (path2, path3) const fileName2 = path.resolve (path2, path3) console.log (fileName1); / / asd\ sad\ My\ DCCconsole.log (fileName2); / /\ My\ DCC

The generated path is normalized and the trailing slash is deleted unless the path is resolved to the root directory

Const path = require ('path') const path2 =' / USER/ASUS'const path3 = 'My/DCC/'path.join (path2, path3) / /\ USER\ ASUS\ My\ DCC\ path.resolve (path2, path3) / /\ USER\ ASUS\ My\ DCC

The path.resolve method is also widely used in webpack.

For example, when we use craco to configure path aliases in the react project

Using ES Module can also introduce core modules in node.

As mentioned above, modules that ES Module imports into CommonJS are allowed, so naturally you can also import core modules embedded in node.

/ / test.mjsimport path from 'path'console.log (path); / / normal path object built-in module fs

Fs is an acronym for File System and stands for file system

Any language or framework that serves the server side usually has its own file system

Because the server needs to put all kinds of data, files, etc. In different places.

For example, most of the user data may be put in the database.

For example, some configuration files or user resources (pictures, audio and video) exist on the operating system in the form of files.

Node also has its own file system operation module, which is fs.

With the help of the file system encapsulated by Node, we can manipulate files directly on any operating system (windows, Mac OS, Linux).

This is one of the big reasons why Node can develop servers, and why it can become a popular tool such as front-end automation scripts.

Introduction to API of fs

Most API provide three modes of operation:

Method 1: synchronize the operation file-the code will be blocked and will not continue to execute

Const fs = require ('fs') const filename ='. / test.html'const file = fs.statSync (filename) console.log (file)

The statSync method can read our file information synchronously and return an fs.Stats instance.

Method 2: asynchronous callback function operation file-the code will not be blocked, and the callback function needs to be passed in. When the result is obtained, the callback function is executed.

How to use fs.stat: fs.stat (path, callback). The callback takes two parameters (err and stats), which reads the file asynchronously and executes our callback function after an error occurs or after the reading is completed.

Const fs = require ('fs') const filename ='. / two parameters of the test.html'// callback function, one is the error message, the other is the file information const file = fs.stat (filename, (err, info) = > {console.log (info); / / Stats class}) console.log (file); / / undefined, because it is asynchronous, it does not block code execution, and the file information has not been obtained when printing

Method 3: asynchronous Promise operation file-the code will not be blocked. If the method operation is called through fs.promises, a Promise will be returned, which can be processed through then and catch.

Many api provide promise mode, but not all of them, so you can consult the documentation before using something.

Const fs = require ('fs') const filename ='. / test.html'// fs.promises is an object in the fs module, and many of its methods are based on promise's const file = fs.promises.stat (filename). Then (res = > {console.log (res); / / Status class}) .catch (err = > {console.log (err);}) console.log (file); / / Promise {}

File descriptor

What is the file descriptor File desciptors?

On POSIX systems, for each process, the kernel maintains a table of currently open files and resources

Each open file is assigned a simple numeric identifier called a file descriptor

At the system level, all file system operations use these text descriptors to identify and track each specific file.

The Windows system uses a different but conceptually similar mechanism to track resources

To simplify the user's work, Node.js abstracts specific differences between operating systems and assigns a numeric file descriptor to all open files. In other words, the api in node blocks out a lot of text descriptors, which is equivalent to doing these operations for you internally.

The fs.open () method is used to assign a new file descriptor

Once assigned, the file descriptor can be used to read data from the file, write to the file, or request information about the file

Const fs = require ('fs') const filename ='. / test.html'fs.open (filename, (err, fd) = > {console.log (fd); / / 4 / / read the corresponding file information fs.fstat (fd, (err, info) = > {console.log (info); / / Stats object})})

Reading and writing of documents

If we go offline to manipulate the contents of the file, we can use the read and write of the file at this time.

Fs.readFile (path, options, callback): read the contents of a file

Fs.wraiteFile (file, data, options, callback): write content to a file

1. File write

Const fs = require ('fs') fs.writeFile ('. / a.txttle), 'Hello!' , err = > {console.log (err);})

We didn't have this file originally, but since the flag attribute in the options parameter defaults to w, it will automatically create a file for us and write the corresponding value to

In the above code, you will find that there is a curly brace that does not fill in anything. This is the options parameter that was filled in when writing.

Flag: the way to write. Default is'w'.

'r'-opens the file in read mode. An exception occurs if the file does not exist

'ringing'- opens the file in read-write mode. An exception occurs if the file does not exist

'rs+'-opens the file in synchronous read-write mode. Command the operating system to bypass the local file system cache

'w'-opens the file in write mode. The file will be created (if it does not exist) or truncated (if it exists)

'wx'-similar to' wicked, but failed if path exists

'wicked'- Open the file in read-write mode. The file is created (if the file does not exist) or truncated (if the file exists).

'wx+'-similar to' wicked subscription, but failed if path exists

'a'- opens the file in append mode. If the file does not exist, it will be created

'ax'-similar to 'aura, but failed if path exists

'asides'- opens the file in read and append mode. If the file does not exist, it will be created

'ax+'-similar to' aura', but fails if path exists

Const fs = require ('fs') fs.writeFile ('. / a.txttle), 'Hello!' , {flag: 'averse'}, err = > {console.log (err);})

After we changed flag to a +, all we did was append the file, and found that the text we wanted to write appeared at the end of the target file.

Encoding: encoding of characters. Default is' utf8'.

two。 File reading

When reading a file, if you do not enter encoding, the result returned is Buffer, which is similar to a string of binary codes

Because in the fs.readFile method, the default value of the encoding property is null, that is, it does not have a default value, which needs to be specified manually, and the default value of its flag is'r'.

Const fs = require ('fs') / / does not specify encoding, so he does not know which character encoding format to read the file fs.readFile ('. / a.txtencoding, (err, data) = > {console.log (data); / /}) fs.readFile ('. / a.txtencoding, {encoding: 'utf-8'}, (err, data) = > {console.log (data); / / Hello! Hello! Hello! })

Folder operation

1. Create a new folder-fs.mkdir (path [, mode], callback)

Const fs = require ('fs') const path = require (' path') / / absolute path const targetDir = path.resolve (_ _ dirname, 'dcc') try {fs.mkdirSync (targetDir)} catch (err) {console.log (err) } / / relative path const dirname ='. / dcc'// fs module has an existsSync method to determine whether the path corresponding to the current parameter exists if (! fs.existsSync (dirname)) {fs.mkdir (dirname, err = > {console.log (err);})}

It is found that the corresponding folder has been created. If we execute the program again, we will find an error, indicating that the same folder cannot be created repeatedly. It also shows that when we use the fs.mkdir method to create files, we can pass in either absolute path or relative path.

two。 Get all the files in the folder-fs.readdir (path [, options], callback)

Const fs = require ('fs') fs.readdir ('. / dcc', (err, files) = > {/ / it reads an array of files, including directories that can also be read to console.log (files); / / ['a.htmlcards,' b.txtlegs, 'c.mdlines, dir]})

Think about it: what if we want to read all the files in this folder now, such as files in other folders in the folder?

In fact, we can pass the corresponding file type when the readdir method reads the file under the directory by passing in parameters, that is, changing the withFileTypes property corresponding to options to true.

Then each file information corresponds to a Dirent object, and there is an isDirectory method (on the prototype) in each object to determine whether the current file is a folder, as shown in the following figure:

Since there may be a set of folders in the folder, it must be implemented recursively if you want to read out the paths of all the files.

Const fs = require ('fs') const path = require (' path') const getFileName = (dirname) = > {/ / read all the file names under this path according to the directory path, / / the withFileTypes attribute is changed to true to expose its file type by the way when reading the file name / / the file type is not an attribute under the Dirent object Instead, we need to get fs.readdir (dirname, {withFileTypes: true}, (err, files) = > {files.forEach (file = > {/ / every Dirent object has an isDirectory method to determine whether the file is a folder if (file.isDirectory ()) {/ / if the current file is still a folder, we need to find its path through the resolve method. Then recursively call the function const filePath = path.resolve (dirname, file.name) getFileName (filePath) / / instead of a folder, just print the name directly} else {console.log (file.name) })})} getFileName ('. / dcc')

From the print result, we can see that all the file names under a directory have been printed recursively.

3. Folder renaming

Renaming may require running the editor as an administrator to be allowed

Const fs = require ('fs') fs.rename ('. / dcc','. / kobe', err = > {console.log (err);})

Replication case of folder

Scene: there are many folders in a folder, and there are many files in each folder. It is required that these files be selected and copied to another folder with the specified suffix according to the original file directory format.

Const fs = require ('fs') const path = require (' path') / / get the starting file path and destination file path const startPath = process.argv [2] const endPath = process.argv [3] const ext = process.argv [4] | | '.js' / / get the file const allDirs = fs.readdirSync (startPath) / / traverse the actual folder and take out his subfolder for (const name of allDirs) {/ / path to the original folder const originDir = path.resolve (startPath Name) / / get the folder path const targetDirname = path.resolve (endPath, name) / / after being copied in the past / / by determining whether this path exists To decide whether to create a new folder or not. If it exists, the file has already been created. Just skip to create the next folder and if (fs.existsSync (targetDirname)) continue. / / create a new folder fs.mkdirSync (targetDirname) / / read the files in the corresponding folder const currDirFiles = fs.readdirSync (originDir) / / traverse the folder under the destination path Get all the files for (const name of currDirFiles) {/ / determine whether the suffix of the current file is to copy the past file if (path.extname (name) = ext) {/ / splice to get the path of the original file and the path of the copied past file const originCopyName = path.resolve (originDir, name) const targetCopyName = path.resolve (targetDirname, name) / / copy the file using copyFileSync method It receives two parameters, one is the name of the source file to be copied, and the other is the target file name of the copy operation, fs.copyFileSync (originCopyName, targetCopyName) console.log ('copy successful!') }}}

When we execute the command node test.js. / dir1. / dir2 .txt, we find that all the files with the suffix txt have been copied, indicating that there is nothing wrong with our program.

Events module

Events basic method

The core API in Node is based on asynchronous event-driven

In this system, some of your objects (Emitters) emit an event.

We can listen to this event (the Listeners), and the callback function passed in will be called when the event is triggered

Both emitting and listening events are done through the EventEmitter class, and they belong to the events object

Emitter.on (eventName, listener): listen for events, or use addListener

Emitter.off (eventName, listener): remove listening events, or use removeListener

Emitter.emit (eventName [,... args]): emits an event that can carry some parameters

What we import from the events module is different from the other modules because it is a class. We can create an "emitter" from this class.

Const EmitterEmitter = require ('events') console.log (EmitterEmitter); const emitter = new EmitterEmitter ()

Through the transmitter, we can monitor, cancel and transmit the corresponding events.

Multiple identical events can be listened to at the same time, and all bound functions will be executed.

When launching an event, you can carry multiple parameters. In the callback function of listening, we can use. The rest operator to centralize them into a variable

If the binding is the same event, then the trigger will be executed in the order of listening. The following code is to execute "I was clicked 1" first, and then "I was clicked 2".

/ / addEventListener is the acronym emitter.on for on ('click', (... args) = > {console.log (' I was clicked, args) / / output after 2s: I was clicked 1 ['kobe',' james']}) / / if all the events bound are the same, then the emitter.on ('click', (... args) = > {console.log (' I was clicked 2percent, args) is executed in the order in which the event is triggered. / output after 2s: I was clicked 2 ['kobe',' james']}) setTimeout (() = > {emitter.emit ('click',' kobe', 'james') / / launch event, which can carry parameters}, 2000)

If we rewrite the function in setTimeout and then extract the callback function of the second registered event, what happens to the printed result?

/ / addEventListener is an acronym for on emitter.on ('click', (... args) = > {console.log (' I was clicked on a button, args);}) const clickFn = (. Args) = > {console.log ('I was clicked on a second, args) } emitter.on ('click', clickFn) setTimeout () = > {emitter.emit (' click', 'kobe',' james') emitter.off ('click', clickFn) emitter.emit (' click', 'kobe',' james')}, 2000)

On the first launch event, both registered events will be triggered, but when we cancel the second registered event using emitter.off, the second event will not be triggered the next time the same event is launched.

Events acquires information

Emitter.eventNames (eventName) returns an array of events that list the trigger's registered listeners

Emitter.listenerCount (eventName) returns the number of listeners that are listening for an event named eventName

Emitter.listeners (eventName) returns a copy of the listener array of events named eventName

Const EmitterEmitter = require ('events') const emitter = new EmitterEmitter () emitter.on (' click', (... args) = > {console.log ('I was clicked on 1 click, args);}) const clickFn = (. Args) = > {console.log ('I was clicked on 2 games, args);} emitter.on ('click', clickFn) emitter.on (' tab', clickFn) console.log (emitter.eventNames ()) / ['click',' tab'] console.log (emitter.listenerCount ('click')); / / 2console.log (emitter.listeners (' click')); / / [[Function (anonymous)], [Function: clickFn]]

Methods are not commonly used in events

Events bound by emitter.once listen only once. Add a single listener function to an event named eventName. The next time the eventName event is triggered, the listener will be removed and then called

Const EmitterEmitter = require ('events') const emitter = new EmitterEmitter () emitter.once (' click', (... args) = > {console.log ('I was clicked on a button, args) }) setTimeout (() = > {/ / the emission of this event will execute the emitter.once bound function emitter.emit ('click',' kobe', 'james') / / the emission of the second event will not execute the emitter.once bound function emitter.emit (' click', 'kobe',' james')}, 500)

Emitter.prependListener adds the listening event to the top, but adds the listener function to the beginning of the listener array for the event named eventName. Does not check if listener has been added. Multiple calls and passing in the same eventName and listener will cause listener to be added and called multiple times

Const EmitterEmitter = require ('events') const emitter = new EmitterEmitter () emitter.on (' click', (... args) = > {console.log ('I was clicked on an args);}) / / the function bound by the prependListener method executes emitter.prependListener earlier than the callback function bound with on ('click', (... args) = > {console.log (' I was clicked 2percent, args)) }) setTimeout (() = > {emitter.emit ('click',' kobe', 'james')}, 500)

Mitter.prependOnceListener: add listening events to the front, but only listen once

Emitter.removeAllListeners ([eventName]) removes all or specified eventName listeners; note that it is a bad practice to remove listeners added elsewhere in the code, especially if the EventEmitter instance is created by another component or module (such as socket or file stream).

At this point, I believe you have a deeper understanding of "what are the common built-in modules in Node.js?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report