I. Built-in module PATH
1.1. Know the PATH module
The path module is used to manipulate paths and files and provides many useful methods.
And we know that the paths are different on Mac OS, Linux, and Windows
- Window will use
\
or\ \
To be used as a delimiter for the file path, which is currently supported/
; - Mac OS, Linux, Unix operating system
/
To be the delimiter for the file path;
So what if we develop an application that uses \ as the delimiter on Windows and deploy it to Linux?
- There are some problems with the display path;
- So in order to mask the differences between them, we can use the operation of paths during development
path
Module;
1.2. Path Common apis
Get information from the path
- Dirname: Gets the parent folder of the file;
- Basename: Obtains the file name.
- Extname: obtain the file extension.
const path = require("path");
const myPath = '/ Users/coderwhy/Desktop/Node/class/PPT / 01 _ encounter Node. The PDF';
const dirname = path.dirname(myPath);
const basename = path.basename(myPath);
const extname = path.extname(myPath);
console.log(dirname); / / / Users/coderwhy/Desktop/Node/class/powerpoint
console.log(basename); // 01_ encounter node.pdf
console.log(extname); // .pdf
Copy the code
Stitching of paths
- If we want to concatenate multiple paths, different operating systems may use different separators;
- We can use it at this point
path.join
Functions;
console.log(path.join('/user'.'why'.'abc.txt'));
Copy the code
Concatenate files with a folder
- This can be used if we want to concatenate a file and folder
path.resolve
;resolve
The function will determine if there is one in front of our concatenated path/
or../
or. /
;- If the representation is an absolute path, the corresponding splicing path is returned.
- If not, the path will be concatenated with the folder where the current execution file resides
path.resolve('abc.txt'); / / / Users/coderwhy/Desktop/Node/TestCode / 04 _learn_node / 06 _ _ common built-in module / 02 file path/ABC. TXT
path.resolve('/abc.txt'); // /abc.txt
path.resolve('/User/why'.'abc.txt'); // /User/why/abc.txt
path.resolve('User/why'.'abc.txt'); / / / Users/coderwhy/Desktop/Node/TestCode / 04 _learn_node / 06 _ _ common built-in module / 02 file path/User/according to ABC. TXT
Copy the code
Resolve will also be used in webpack:
const CracoLessPlugin = require('craco-less');
const path = require("path");
const resolve = dir= > path.resolve(__dirname, dir);
module.exports = {
plugins: [{plugin: CracoLessPlugin,
options: {
lessLoaderOptions: {
lessOptions: {
modifyVars: { '@primary-color': '#1DA57A' },
javascriptEnabled: true,},},},}],webpack: {
alias: {
"@": resolve("src"),
"components": resolve("src/components")}}}Copy the code
Ii. Built-in module FS
1.1. Understand fs module
Fs is short 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, and so on in different places;
- For example, user data may be mostly stored in a database (we’ll learn more about that later).
- For example, some configuration files or user resources (pictures, audio and video) are in the form of files in the operating system;
Node also has its own filesystem manipulation module, fs:
- Node encapsulates the file system so that you can manipulate files directly on any operating system (Windows, Mac OS, Linux).
- This is one of the reasons Node can develop servers, and why it can be a popular tool for things like front-end automation scripts;
The Node file system has many apis: nodejs.org/dist/latest…
- We cannot, and need not, learn individually;
- This should be more as an API query manual, such as when the query can be used;
- In the learning stage, we only need to learn the most common ones;
But most of these apis provide three ways of doing things:
- Method 1: synchronize operation files: the code will be blocked and will not continue execution;
- Method 2: asynchronous callback function operation file: the code is not blocked, the callback function needs to be passed, when the result is obtained, the callback function is executed;
- Method three: asynchronous Promise operation file: code will not block, pass
fs.promises
Calling a method operation returns a Promise, which can be processed by then and catch;
Let’s take the state of a file as an example:
- Note: both need to be introduced
fs
Module;
Method 1: Synchronize files
// 1. Method 1: Read files synchronously
const state = fs.statSync('.. /foo.txt');
console.log(state);
console.log('Subsequent code execution');
Copy the code
Method 2: Asynchronous callback functions operate files
// 2. Mode 2: Read data asynchronously
fs.stat(".. /foo.txt".(err, state) = > {
if (err) {
console.log(err);
return;
}
console.log(state);
})
console.log("Subsequent code execution");
Copy the code
Method three: Asynchronous Promise operation file
// 3
fs.promises.stat(".. /foo.txt").then(state= > {
console.log(state);
}).catch(err= > {
console.log(err);
})
console.log("Subsequent code execution");
Copy the code
In the next code walkthroughs, I’ll use asynchronous callbacks: relatively generic;
1.2. File descriptors
What are File descriptors?
On POSIX systems, the kernel maintains a table of currently open files and resources for each process.
- Each open file is assigned a simple numeric identifier called the file descriptor.
- At the system level, all file system operations use these file descriptors to identify and track each particular file.
- Windows systems use a different but conceptually similar mechanism to track resources.
- To simplify the user’s life, Node.js abstracts out specific differences between operating systems and assigns a numeric file descriptor to all open files.
The fs.open() method is used to assign a new file descriptor. Once assigned, a file descriptor can be used to read data from, write data to, or request information about a file.
// Get the file descriptor
fs.open(".. /foo.txt".'r'.(err, fd) = > {
console.log(fd);
fs.fstat(fd, (err, state) = > {
console.log(state); })})Copy the code
1.3. Read and write files
If we want to manipulate the contents of the file, we can use read and write of the file:
fs.readFile(path[, options], callback)
: Reads the contents of a file.fs.writeFile(file, data[, options], callback)
: Writes to a file.
File write:
fs.writeFile('.. /foo.txt', content, {}, err= > {
console.log(err);
})
Copy the code
In the code above, you can see that there is a curly brace without any content. This is the option parameter to write to:
- Flag: indicates the write mode.
- Encoding: Character encoding.
Let’s start with flag:
- There are many values for flag:Nodejs.org/dist/latest…
w
Open file to write, default;w+
Open the file for reading and writing. If the file does not exist, create it.r+
Open the file for reading and writing, if not present then throw an exception;r
Open the file to read, read the default value;a
Open the file to write, will be exiled at the end of the file. If not, create a file.a+
To open a file for reading and writing, will be exiled at the end of the file. If not, create the file
Let’s look at coding:
- In Jane books before I wrote an article about a character encoding: www.jianshu.com/p/899e749be…
- Currently, utF-8 is basically used;
File reading:
- If encoding is not specified, Buffer is returned;
fs.readFile('.. /foo.txt', {encoding: 'utf-8'}, (err, data) = > {
console.log(data);
})
Copy the code
File reading:
const fs = require('fs');
fs.readFile('.. /foo.txt', {encoding: 'utf-8'}, (err, data) = > {
console.log(data);
})
Copy the code
1.4. Folder operation
Create a new folder
Create a new folder with fs.mkdir() or fs.mkdirsync () :
const fs = require('fs');
const dirname = '.. /why';
if(! fs.existsSync(dirname)) { fs.mkdir(dirname,(err) = > {
console.log(err); })}Copy the code
Gets the contents of the folder
// Read the folder
function readFolders(folder) {
fs.readdir(folder, {withFileTypes: true},(err, files) = > {
files.forEach(file= > {
if (file.isDirectory()) {
const newFolder = path.resolve(dirname, file.name);
readFolders(newFolder);
} else {
console.log(file.name);
}
})
})
}
readFolders(dirname);
Copy the code
File renaming
fs.rename('.. /why'.'.. /coder'.err= > {
console.log(err);
})
Copy the code
Iii. Built-in module Events
3.1. Basic use
The core apis in Node are asynchronous event-driven:
- In this system, some objects (Emitters) emit an event;
- We can listen for this event, and the callbacks passed in, which are called when the event is being listened for;
Emitting events and listening to events are done through the EventEmitter class, which belongs to the Events object.
emitter.on(eventName, listener)
: Listening on events, also availableaddListener
;emitter.off(eventName, listener)
: Removes event listening, also availableremoveListener
;emitter.emit(eventName[, ...args])
: Emits an event, which can carry some parameters;
const EventEmmiter = require('events');
// Listen on events
const bus = new EventEmmiter();
function clickHanlde(args) {
console.log("Listening for the Click event", args);
}
bus.on("click", clickHanlde);
setTimeout(() = > {
bus.emit("click"."coderwhy");
bus.off("click", clickHanlde);
bus.emit("click"."kobe");
}, 2000);
Copy the code
3.2. Common attributes
Instances of EventEmitter have properties that record information:
emitter.eventNames()
: Returns the currentEventEmitter object
Array of registered event strings;emitter.getMaxListeners()
: Returns the currentEventEmitter object
The maximum number of listeners that can passsetMaxListeners()
The default is 10;Emitter. ListenerCount
: Returns the currentEventEmitter object
The name of an event and the number of listeners;2. The notice is an interesting workpiece.2.
: Returns the currentEventEmitter object
An array of all listeners on an event listener
console.log(bus.eventNames());
console.log(bus.getMaxListeners());
console.log(bus.listenerCount("click"));
console.log(bus.listeners("click"));
Copy the code
3.3. Supplement of methodology
Emitter. Once (eventName, listener) : An event listens once
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.once('click'.(args) = > {
console.log("Event detected", args);
})
setTimeout(() = > {
emitter.emit('click'.'coderwhy');
emitter.emit('click'.'coderwhy');
}, 2000);
Copy the code
Emitters. PrependListener () : Adds listening events to the front
emitter.on('click'.(args) = > {
console.log("A monitored event", args);
})
// b listener events are placed first
emitter.prependListener("click".(args) = > {
console.log("B detects event", args);
})
Copy the code
Emitter. PrependOnceListener () : add to monitor events to the front, but listen to only one
emitter.prependOnceListener("click".(args) = > {
console.log("C monitored event", args);
})
Copy the code
Emitter. RemoveAllListeners ([eventName]) : remove all the listeners
// Remove all event listeners on Emitter
emitter.removeAllListeners();
// Remove the click listener on emitter
emitter.removeAllListeners("click");
Copy the code