Skip to content

nextTick ​

Callback ordering depends on where callbacks are scheduled and on event-loop phases, rather than a fixed priority chain. The nextTick queue is processed after the current operation returns; its ordering relative to Promise microtasks also depends on CJS/ESM execution context.

Save the following as a regular CommonJS file to observe ordering within an I/O callback:

js
const fs = require('node:fs');

fs.readFile(__filename, () => {
  process.nextTick(() => console.log('nextTick'));
  Promise.resolve().then(() => console.log('promise'));
  setTimeout(() => console.log('timeout'), 0);
  setImmediate(() => console.log('immediate'));
});
// 此场景:nextTick → promise → immediate → timeout

Do not rely on a fixed order between setTimeout and setImmediate registered in the main module. Interpret timer behavior in the context of the Node version, including the change introduced in Node 20. Node event loop.

module ​

require

if(是否在文件模板缓存区中){
//是
返回extend
}else{
    if(是否原生模块){
        //是
        if(是否在原生模块缓存区中){
            //否
            1.加载原生模块
            2.缓存原生模块
        }else{
            //是
            返回extend
        }
    }esle{
        //否
        1.查找文件模块
        2.根据扩展名载入文件模块
        3.缓存文件模块
        4.返回extend
    }
}
File search ​
开始查找文件

1.查找已缓存路径
2.尝试直接查找该文件
3.尝试添加扩展名后查找该文件
4.尝试根据包查找该文件
5.从包描述文件获取文名 (main入口)
6.查找该目录下的index(js/node)
package ​

In nodejs, packages are used to uniformly manage first-level modules with interdependencies.A package is a directory.

  • package.json package description file
  • binbinary
  • lib stores javascript files
  • doc documentation
  • test unit tests and other tests
npm package management ​
  • npm search xxx Find package
  • npm view gulp view package
  • npm install gulp installation package
  • npm install -g express-generator global installation package npm config ls lists all configurations prefix global installation directory cliconfig command line configuration file userconfig user configuration file builtin built-in configuration file npm root -g View global path
  • npm config set prefix "d:\global" Modify the global path
  • npm list displays all packages in the current directory
  • npm list -g displays all packages globally
  • npm uninstall gulp uninstalls the local version
  • npm uninstall gulp -g uninstalls global packages
  • npm update gulp updates local gulp
  • npm update -g gulp updates gulp globally
  • npm update updates all packages in the current directory
  • npm shrinkwrap prevents the version from being upgraded and uses shrinkwrap to lock dependent versions
  • npm prune removes modules that are not in package.json

Use shrinkwrap to lock dependent versions

6 ways for npm to obtain configuration, priority from high to low ​
命令行参数, --proxy http://server:port 即将proxy的值设为http://server:port
环境变量,以npm_config_为前缀的环境变量将会被认为是npm的配置属性。如设置proxy可以加入这样的环境变量npm_config
用户配置文件。可以通过npm config get userconfig查看文件路径,如果是mac系统的话默认路径就是$HOME/.npmrc.
全局配置文件。可以npm config get globalconfig查看文件路径,mac系统的默认路径是/usr/local/etc/npmrc
内置配置文件。安装npm的目录的的npmrc文件
默认配置。 npm本身有默认配置参数,如果以上5条都没设置,则npm会使用默认参数。
为npm设置代理
- npm config set proxy http://server:port

npm add user Enter username and email to register and publish the package

Release package and some processing

buffer object for binary data processing ​

  • Buffer is a section of memory that temporarily stores input and output data.
  • JavaScript has binary types such as ArrayBuffer and TypedArray; Node.js Buffer provides byte buffers for file and network I/O
  • NodeJS provides a Buffer object to provide operations on binary data
  • It is a global object that represents fixed memory allocation, which means that the number of bytes to be placed in the cache needs to be determined in advance.

The differences between several stream reading and writing methods in the fs module ​

text
                             异步           同步

- 将文件作为整体读入缓存区    readFile    readFileSync
- 将文件部分读入缓存区        read         readSync
- 将数据完整写入文件          writeFile    writeFileSync
- 将缓存区的部分内容写入文件  write         writeSync

stram ​

  • A stream is an ordered set of byte data transmission means with a starting point and an ending point.
  • Don't care about the overall content of the file, only focus on whether the data is read from the file, and the processing after reading the data
  • Stream is an abstract interface implemented by many objects in Node.For example, the request object of an HTTP server is a stream, and stdout is also a stream.
  • Streams are readable, writable, or both.All streams are instances of EventEmitter."Almost every Node program, no matter how simple, uses streams in some way."

stream.Readable readable stream

  • fs.ReadStream reads files

  • http.IncomingMessage client request or server response

  • net.Socket socket object in tcp connection

  • process.stdin standard input stream

  • Gzip data compression

  • There are two types of readable streams, with internal flowing (flowing) steps and non-flowing (pause) mode to read data.

  • flowing mode uses the operating system's internal IO mechanism to read data and provide it to you as quickly as possible

  • In non-flowing mode, the stream is in the pause step by default, and the read method must be explicitly called to read data.

"Attention" If no data event handler is bound and there is no pipe() target and the stream is switched to flowing mode, data will be lost.

middleware ​

  • Middleware is a function that processes HTTP requests and is used to complete various specific tasks, such as checking whether the user is logged in, analyzing data, and other tasks that need to be completed before the data is finally sent to the user.
  • Its biggest feature is that after one middleware has processed it, the corresponding data can be passed to the next middleware.
var express = require('express');
var app = express();
//中央
app.use(function(req,res,next){
    console.log('中央');
  req.mny = 100;
  next();
});

2.Features

    1. Each middleware can control whether the process continues to execute next(); before it continues to execute.
    1. req res same object
    1. If an error occurs, transfer it to the error handling middleware for processing.
  • Set cookie to client via response header Set-Cookie:name=abc
  • Read the cookie from the client Cookie:key1=value1;key2=value2

referer ​

Referer identifies the referring page, but may be omitted or forged; it is not sufficient for authentication or authorization.

etag ​

When there is a problem with the last modified time

1. 某些服务器不能精确得到文件的最后修改时间,这样就无法通过最后修改时间来判断文件是否更新了
2. 某些文件的修改非常频繁,在秒以后的时间内进行修改,Last-Modified只能精确到秒
3. 一些文件的最后修改时间改变了,但是内容并未改弯。我们不希望客户端认为这个文件修改
4. 如果同样的一个文件位于多个CDN服务器上的时候内容虽一样,修改时间不一样

ETag is the abbreviation of entity tag, a string generated based on the entity content, which can identify the status of the resource.When the resource sending changes, the ETag also changes.ETag is generated by the web server and then sent to the browser client.

  1. If the client wants to determine whether the cache is available, it can first obtain the ETag of the document in the cache, and then send a request to the web server through If-None-Match to ask whether the cache is available.
  2. The server receives the request and compares the ETag of the file in the server with the If-None-Match in the request header. If the values are the same, it means that the cache is still the latest. The web server will send a 304 Not Modified response code to the client to indicate that the cache has not been modified and can be used.
  3. If they are different, the web server will send the latest version of the document to the browser client.

How does the browser not send a request? ​

The browser will cache the file into the Cache directory. When making the second request, the browser will first check whether the Cache directory contains the file. If it does, and it has not yet reached the Expires setting time, that is, the file has not expired, then the browser will directly read the file from the Cache directory without sending a request.

  • Expires is the server response message header field. When responding to an http request, it tells the browser that the browser can directly fetch data from the browser cache before the expiration time without requesting again.
  • Cache-Control has the same function as Expires. They both indicate the validity period of the current resource and control whether the browser directly fetches data from the browser cache or resends the request to the server to fetch data. If both are set at the same time, its priority is higher than Expires.

authorization ​

Authentication: Authentication is the process of verifying that a user is who he or she claims to be. Authorization: Authorization is to determine whether the user has the right to do something.