1. What is Node?
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine .
No need to deal with compatibility issues 2009.05
1.1Node is a JS operating environment
How js works:
1. Client: Import the js file, then open the browser and view it in the console
2.node server:
1. In the cmd window, use the cd command to switch to the folder that needs to be opened, and run the node file name
2. Shift + right click directly under the folder
3. The vscode editor is directly opened in the terminal of the current file, and the submint editor needs to install the terminal plug-in
1.2 Comparing JS in the browser
1.2.1 JS in the browser
web api provides functions for manipulating browser windows and pages. For example: BOM manipulation, DOM manipulation, AJAX
These features have limitations. For example: cross-domain issues, file reading and writing
1.2.2 JavaScript in Node
nodeAPI provides almost everything that can be done
1.2.3 JS in Node vs. JS in the browser
① The browser provides limited capabilities, and JS can only use the functions provided by the browser to do limited operations
② Node provides a complete ability to control the computer. NodeJS can almost control the entire operating system through the interface provided by Node.
1.3 Official documents
Node official website: https://nodejs.org/en/
Node Chinese official website (private website): http://nodejs.cn
2. What can Node do?
2.1 Developing desktop applications
For example, QQ, WeChat... VScode, which is often used, is developed with node
2.2 Developing server applications
Structure 1: Microstructure
The Node server needs to complete request processing, response, interaction with database, and various business logics
This structure is usually applied to micro sites. For example: personal blog, company official website
Structure 2: Large Structures
This structure is very common and is used on sites of all sizes
Node server
Do not do anything related to business logic. Most of the time, it is simply forwarding the request. but may have some extra features
1. Simple information records: request logs, user preferences, advertising information
2. Static resource hosting
3. Cache
backend server
Handle large business logic
3. Why learn NodeJS?
1. JS development saves time and effort
2. Because nodeJS is single-threaded, there is no loss of thread switching and no competition between threads.
3. IO processing is very fast
4. Node is not suitable for complex operations, for example, java can open multiple threads for parallel operations
Node can do everything that other server-side languages (such as java, .net) can do. Language is not good or bad, only suitable for the scene.
Node developers are looking for a fast IO processing language, so they choose JavaScript
4. Global object
global
Same as this in the browser environment, representing the top-level object
Note: the browser's global environment this means window, this in node does not mean global
// 全局对象
console.log(global)
console.log(this)//在node中的this不指向window,就是一个空对象
var a = 123;
console.log(global.a == a)//在node中变量声明不提升至global中
console.log(a)
1.setTimeout,setInterval
The usage is exactly the same as the browser environment.
Note: The browser returns the ID, and the object is returned in the node environment
2.setImmediate
Similar to setTimeout 0
setInterval(()=>{
console.log(123)
},1000)
setTimeout(() => {
console.log("延时定时器")
},0);
setImmediate(()=>{
console.log("qwe")
},0)
3.console
The browser outputs in the console
node output on the command line
4.__address*
console.log(__dirname)
Get the directory where the current module is located
Note : not a global attribute
5.__filename*
console.log(__filename)
Get the file path of the current module
Note : not a global attribute
6.Buffer
Buffer is similar to an array, it is a data transmission format, the difference between hexadecimal numbers and strings:
the string is read-only, and a new string can be obtained by modifying the string, and the original string remains in the original
buffer memory The allocation is not in the heap memory of v8, and the application of separate memory is realized at the c++ level in node.
Typed array
Inherited from UInt8Array
The basic unit of storage in a computer: byte
It may be necessary to use hexadecimal representation when using and outputting
7.process
cwd()
Return the working directory of the current nodejs process, the directory of the running cmd window
exit()*
Force quit the current node process
The exit code can be passed in, 0 means successful exit, the default is 0, mainly for input into the log
argv*
Get all parameters in the command
platform
Get the current platform system
kill(pid)
Kill the process according to the process ID
env
Get the environment variable object
5. Node modularization
1. Module search
1. Relative path
2.1 Add./ Situation
On the server side, be sure to add ./, which means starting from the current directory
2.2 Without ./case
① Check whether it is a built-in module, such as: fs, path, etc.
② Check the node_modules in the current directory
③ Check the node_modules in the parent directory
3. Suffix name
If no suffix is provided, auto-completion
The order of completion is: js, json, node, mjs
4. File name
If only a directory is provided and no file name is provided, index.js in this directory will be automatically searched
5. Run node ./
The main field in package.json, the default value is index.js
2. module object
Record the information of the current module
3. require function
The resolve function is spliced into an absolute path
4. Modular principle
When executing a module or using require, the module is placed in a function environment
6. Basic built-in modules
(After downloading the number node, it will automatically package the module for you)
1.os
Reference address: https://nodejs.org/dist/latest-v12.x/docs/api/os.html
1.EOL
Operating system version
2.arch()
Operating system CPU architecture
3.cpus()
CPU core information
4.freemem()
How much memory is left in the computer, returned as bytes
5.homedir()
User directory
6.hostname()
hostname
7.tmpdir()
Get temporary file directory
2.path
Reference address: https://nodejs.org/dist/latest-v12.x/docs/api/path.html
Note : The operations of the path module are all equivalent to string operations, and will not determine whether the path actually exists
1.basename
Get the last/behind content of a certain path
The second parameter is an optional parameter, if it matches, remove the matching content
2.sep
operating system delimiter
3.delimiter
Output the separator of the current operating system
4. dirname
Get the directory of the path
5.extname
Get the suffix of the path
6.join
The splicing path will be spliced according to the operating system
7.normalize
According to the operating system specification path
8.relative
Change to a relative path format
9.resolve*
Convert to an absolute path, splicing according to the cmd window
Note : Compared with command-line tools, it is generally used with __dirname
3.url
Reference address: https://nodejs.org/dist/latest-v12.x/docs/api/url.html
1.parse()*
convert string to object
2.format()
object converted to string
4.util
Reference address: https://nodejs.org/dist/latest-v12.x/docs/api/util.html
1.callbackify
Convert asynchronous function to callback form
2.promisify
The callback form is converted into an asynchronous function
3.isDeepStrictEqual
Depth comparison of two objects
7. Document I/O
1. I/O:input output
Input and output to external devices (disks, network cards, graphics cards, printers...)
The speed of IO is often lower than the interaction speed of memory and CPU
2. fs module
Reference address: https://nodejs.org/dist/latest-v12.x/docs/api/fs.html
1. fs.readFile
read a file
2. fs.writeFile
Write content to the file
If the file
3.fs.stat
Get file or directory information
1.size
Occupied bytes
2.atime
Last Access Time
3.mtime
Last time the content of the file was modified
4.ctime
Last time the file status was modified
5.birthtime
File creation time
6.isDirectory()
Determine whether it is a directory
7.isFile()
Determine whether it is a file
4.fs.readdir
Get files and subdirectories in a directory
5.fs.mkdir
Create directory
6.fs.exists
Determine whether a file or directory exists
Eight. Front-end interview questions (1)
1. Implement setInterval with setTimeout
function mySetTimout(fn, delay) {
let timer = null
const interval = () => {
fn()
timer = setTimeout(interval, delay)
}
setTimeout(interval, delay)
}
// 测试
const { cancel } = mySetTimout(() => console.log(888), 1000)
2. Implement setTimeout with setInterval
function mySetInterval(fn, delay) {
const timer = setInterval(() => {
fn()
// clearTimeout(timer)
clearInterval(timer)
}, delay)
}
// 测试
mySetInterval(() => console.log(888), 1000)