JavaScript
This article provides a detailed introduction to advanced JavaScript and Node.js features, including scope, garbage collection, closures, Promises, modules, the HTTP module, and the Express framework. It also explores Webpack configuration and usage in depth. The article systematically explains key technologies and best practices in modern JavaScript development, covering a wide range of topics from basic syntax to build tooling. It is a valuable reference for developers seeking a deeper understanding of the JavaScript ecosystem and ways to improve their development skills.
Advanced JavaScript
Scope
Scope defines the range in which variables can be accessed. In JavaScript, there are two main types of scope:
- Global scope
- Local scope
- Function scope
- Block scope
Local scope:
Variables declared with
letorconstfollow scope rules. Variables declared with thevarkeyword do not, becausevaris hoisted.
Global scope:
Variables declared at the top level of a
<script>tag or.jsfile are in the global scope.Variables in the global scope can be accessed from anywhere.
Not recommended: defining properties on the
windowobject or declaring variables without using any keyword.
Scope chain:
A scope chain is essentially the mechanism used to look up variables.
When a function executes, it first searches the nearest scope, then searches each outer scope in turn until it reaches the global scope.
JavaScript garbage collection:
Memory lifecycle: allocation > use > reclamation
Global variables are generally not reclaimed. Local variables are automatically reclaimed when they are no longer used.
内存泄漏: Memory allocated by a program that cannot be released for some reason is called a memory leak.
Garbage collection algorithms:
- Reference counting (deprecated): tracks the number of references; when the count reaches 0, the memory is reclaimed.
- Problem: circular references
- Mark-and-sweep: starts searching from the roots; if a variable cannot be reached, it is reclaimed.
Closures:
When an inner function uses an outer variable, causing the function to be bound to the surrounding references, this is called a closure.
Variable hoisting:
Before code executes, variables declared with
varare hoisted to the top of the current scope. (Only the declarations are hoisted.)Variable hoisting often leads to various issues, so
letandconstwere later introduced for declaring variables.
Functions
Function hoisting:
Before code executes, function declarations are hoisted to the top of the current scope.
Dynamic function arguments:
Functions have a built-in
argumentsvariable, whose contents are an array-like object.
function getSum() {
let sum = 0;
Array.from(arguments).forEach(item => {
sum += item;
})
console.log(sum);
}
getSum(1, 2, 3)
Rest parameters are not pseudo-arrays.
function getSum(...arr) {
let sum = 0;
arr.forEach(item => {
sum += item;
})
console.log(sum);
}
getSum(1, 2, 3)
Spread Operator and Rest Parameters
function getSum(arr) {
console.log(...arr); // 1 2 3
}
getSum([1, 2, 3])
// 使用场景 某些不支持数组的api可以使用...展开比如
Math.max(...arr)
arr = [...arr1,...arr2]
Arrow functions
Arrow functions do not have their own
this; they look up the scope chain. In a regular function,thisrefers to the caller.
Destructuring assignment
// 数组解构
let arr = [1, 2, 3]
let [a, b, c] = arr
console.log(a,b,c);
// 交换变量
let a = 1
let b = 2
;[a,b] = [b,a]
// 对象解构
let obj={
username:"admin",
password:"123456"
}
let {username,password} = obj
console.log(username);
console.log(password);
Commonly used array functions:


Commonly used string functions:

Debouncing
function debounce(func, delay) {
let timer; // 定时器
return function () {
let context = this; // 记录 this 值,防止在回调函数中丢失
let args = arguments; // 函数参数
//如果定时器存在,则清除定时器(如果没有,也没必要进行处理)
timer ? clearTimeout(timer) : null;
timer = setTimeout(() => {
// 防止 this 值变为 window
func.apply(context, args)
}, delay);
}
}
Rate Limiting
const throttle = (func, limit) => {
let inThrottle; // 是否处于节流限制时间内
return function() {
const context = this;
const args = arguments;
// 跳出时间限制
if (!inThrottle) {
func.apply(context, args); // 执行回调
inThrottle = true;
// 开启定时器计时
setTimeout(() => inThrottle = false, limit);
}
}
}
Promise
- Promise itself is a constructor; a Promise instance represents an asynchronous operation.
- Promise’s prototype contains the
.then(),.catch(), and.finally()functions.then(result => {} [, error => {}])
Special case (resolving callback hell)
Return a Promise object in the first
then, and you can continue chaining.then()calls.
You can also use the
catchfunction to catch exceptions in thethen()chain (from anythen).
Promise.all(Array: Promise)can run multiple asynchronous operations in parallel, then wait until all of them have finished before performing subsequent operations withthen...
Promise.race(Array: Promise)is similar toall, but does not keep waiting after one operation completes. Instead, it passes the return value of the first operation to complete to thethenfunction, which is called only once.
example:
function getFile(filePath){
return new Promise(()=>{
fs.readFile(...)
})
}
Notes on Using async/await
If
awaitis used inside a function, the function must be marked asasync.
In an async method, code before the firstawaitruns synchronously, while code afterawaitruns asynchronously.
Node JS
fs File System Module
readFile: Read a file
writeFile: Write a file
const fs = require("fs")
console.log(fs);
fs.readFile('./index.html','utf8', (err,file) => {
if(!err){
console.log(file);
}else{
console.log(err.message);
}
})
log("write:")
fs.writeFile('./index.html', 'testtesttest', (err) => {
// fs.writeFile('./index.html', 'testtesttest', { flag: 'a+' }, (err) => {
if (err) {
console.log(err.message);
}else{
console.log('success');
}
})
Path Module
When concatenating paths, using
+can easily produce an invalid path.For example, the path may contain
./or../, or you may forget a/. It is recommended to use thejoinfunction to concatenate paths.
join()concatenates multiple paths into one complete path.basename(dir[, removeStr])extracts the filename from a file path.- If the path is a directory, it returns the directory name.
removeStris used to remove the extension.
extname()gets the file extension.
const path = require("path")
let result = path.join("/test/dir1","/e", "../", "d")
console.log(result);
// __dirname 表示当前程序的运行目录
console.log(__dirname);
HTTP Request Module
The HTTP module can be used to create a server that provides services to external clients.
const { log } = require('console');
const http = require('http');
const server = http.createServer();
server.on('request',(req,res) =>{
log(req)
log(res)
res.end('end.')
})
server.listen(80,()=>{
console.log("The server is runing on http://127.0.0.1:80");
})
Modularization
Modules in Node.js are generally divided into three categories:
- Built-in modules (such as
fsandpath) - Custom modules (JavaScript files)
- Third-party modules (which need to be downloaded)
Ways to load modules
//加载内置模块
const fs = require('fs')
//加载用户模块
const custom = require('./custom.js')
//加载第三方模块
const axios = require('axios')
Module Scope
Function variables defined in a custom module can only be used within that module. This module-level restriction is called module scope.
It effectively prevents global variable pollution.
// 默认导出的对象为{} 我们需要将需要导入的对象添加到exports上去
module.exports.属性 = 值
// 或者
module.exports = {...}
// 注意 后者会覆盖前者
Node provides an
exportsobject. By default,exportsandmodule.exportspoint to the same object. If they differ, the object pointed to bymodule.exportstakes precedence.
CommonJS Specification
Inside each module, the module variable represents the current module.
The module variable is an object, and its exports property (that is, module.exports) is the module’s public interface.
Loading a module actually means loading that module’s module.exports property. The require() method is used to load modules.
npm and Packages
In Node.js, third-party modules are also called packages; they refer to the same thing.
Packages are developed by third parties or teams. https://www.npmjs.com (the world’s largest package-sharing platform)
Packages are built by encapsulating built-in modules. They provide more convenient APIs and greatly improve development efficiency.
How to get packages:
Download them using the npm tool. npm comes bundled with Node by default, so no additional installation is required.
# 指定版本号安装依赖
npm i moment@版本号
# 不指定默认最新
npm i moment
# 按照package.json中定义的包去下载
npm i
# 卸载包
npm uninstall 包
# 安装到dev分支
npm i .. -D
npm i .. --save-dev
# 管理全局包
npm i .. -g
npm uninstall .. -g
Package Versioning:
A package version is represented as three dot-separated numbers, for example: 2.24.0
First number: major version
Second number: feature version
Third number: bug-fix version
Version number increment rules:
Whenever an earlier number increases, all subsequent numbers must be reset to zero.
Quickly Create a package.json File
npm init -y
Do not run this in a Chinese-named directory; the directory name must not contain spaces.
When you run
npm install, package information will be automatically recorded inpackage.json.
Analyze the package.json file.
{
"dependencies": {
// 开发和运行都需要用的包
"moment": "^2.30.1"
},
"devDependencies": {
// 只要开发时会使用的包,比如tauri,node-sass等打包编译用到的一些依赖
// 运行时不会包含这些依赖
},
"name": "js",
"version": "1.0.0",
"main": "main.js",
"scripts": {
"dev": "node main.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": ""
}
Package categories:
- Project packages
- Development dependency packages
- Core dependency packages
- Global packages
Package lookup mechanism
Filename extensions: js/json/node
If
./or../is not specified, Node searches from the root-levelnode_modulesdirectory upward through parent directories’node_modulesdirectories.
Express
Express is a fast, open, minimalist web development framework based on Node.js.
It offers even greater development efficiency than the HTTP module.
Installation
npm i express
Use
const express = require('express')
const app = express()
app.listen(80,()=>{
console.log('.....')
})
Listen for Requests
app.get('url',(req,res) => {
...
})
Dynamic Path Parameters
'/user/:id/:username'
//数据将存在以下对象中
req.params.id
Hosted Static Assets
app.use(express.static('public'))
# 路径前缀
app.use('/static',express.static('public'))
nodemon
Hot-reload plugin
nodemon app.js
Example
Enable module support: "type": "module"
app.js
import express from 'express'
import userRouter from './controller/user_controller.js'
const app = express()
app.use('/', userRouter)
app.listen(8080, () => {
console.log('server running on port 8080...')
})
user_service
import db from '../utils/db.js'
export async function getAllUser(req, res) {
const [rows] = await db.query('select * from user')
res.send({
code: 200,
msg: 'success',
data: rows
})
}
user_controller
import express from 'express';
import { getAllUser } from '../service/user_service.js';
const router = express.Router()
router.get('/user', getAllUser)
export default router
Webpack
Webpack emerged to address the complexity and diverse needs of modern web development by providing an efficient, unified, and extensible solution. It greatly improves development efficiency and code quality, allowing developers to focus on business logic rather than the details of building and dependency management.
It supports ES6 module syntax and bundles it into syntax supported by browsers.
Getting Started Example
## count
export default function count(x,y){
return x + y;
}
## sum
export default function sum(...args){
return args.reduce((pre,cur) => {
return pre + cur
},0)
}
## main
import count from "./js/count";
import sum from "./js/sum";
console.log(count(2, 3));
console.log(sum(3, 4, 4, 4, 4, 5));
# 安装webpack依赖
npm i webpack webpack-cli -D
# 通过npx 调用项目中bin目录的命令
npx webpack ./src/main.js --mode=devlopment
Two Packaging Modes
--mode=development # Compile only, no minification
--mode=production # Compile and minify
Basic Configuration
- enty (entry)
Specifies which file Webpack starts bundling from. - output
Specifies where the bundled files are output, how they are named, and so on. - loader
Webpack can only process resources such as JS and JSON by itself. Other resources require loaders so Webpack can parse them. - plugins
Extend Nebpack’s functionality. - mode
There are two main modes:- Development mode: development
- Production mode: production
const path = require('path') //使用path模块完成路径转换
# 入口(entry)出口(output)mode (开发:development,生产:production)
loader(加载器)plugins(插件)
module.exports = {
entry: './src/main.js', //相对路径
output: {
path: path.resolve(__dirname,'dist'), //绝对路径
filename: 'main.js'
},
module:{
rules:[
],
},
plugins:[
],
mode: 'development'
}
Introduction to Development Mode
As the name suggests, development mode is used during the development phase.
There are two main things done in this mode:
- Compile code so that the browser can run it
- Check code quality and establish coding standards
- eslint
- Indentation
webpack-dev-server
webpack-dev-server is a development server based on Express.js. It provides a solution for live reloading and Hot Module Replacement (HMR) in a development environment.
npm install webpack-dev-server -D
npx webpack serve
// or
"scripts": {
"dev": "webpack serve"
},
The generated code is stored in memory and updates automatically whenever the code is updated.
Configure the browser to start automatically.
## webpack.config.js module..
devServer:{
open:true,
host: '127.0.0.1',
port: 88
},
html-webpack-plugin
For working with HTML files separately, the development server does not automatically copy or hot-update HTML files under the src folder.
This plugin can configure this automatically.
It automatically injects the JS files from entry, so you don't need to import them manually. If you import them manually, they will be executed twice.
Installation
npm install html-webpack-plugin -D
yarn add html-webpack-plugin -D
Configuration
## webpack.config.js
const HtmlPlugin = require('html-webpack-plugin')
const htmlPlugin = new HtmlPlugin({
template: './public/index.html',
filename: './index.html'
})
...
plugins:[htmlPlugin ],
Loader
Loaders are the most important part of webpack
By default, webpack can only process JavaScript files. It cannot process other files, so you need to call other loaders to handle them.
- css-loader bundles and processes CSS files
- less-loader bundles and processes Less files
- babel-loader handles advanced syntax in JavaScript that webpack cannot process
Processing CSS files
Install the loader
npm install --save-dev style-loader css-loader
Use the corresponding loader for each configuration file.
## webpack.config.js
rules: [
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
],
For an array in use, webpack invokes the loaders from right to left.
When processing CSS files, the loader ultimately bundles the CSS code into the entry file's code.
Processing Less files
Install
Install the less-loader dependency. Note: less-loader depends on less.
npm i less-loader less -D
Configure
{
test: /\.less$/,
use: [ 'style-loader', 'css-loader', 'less-loader', ]
},
Processing sequence: less-loader > css-loader > style-loader
First, Less compiles the CSS file, then passes it to css-loader. Once the CSS compilation is complete, it is passed to style-loader, and after processing, it is passed to webpack.
Processing files related to URL paths
url-loader -depends on-> file-loader
npm i url-loader file-loader -D
{
test: /\.jpg|png|jpeg$/,
use: [
'url-loader?limit=1024', # 字节
]
}
Handling Advanced JavaScript Syntax
Some advanced syntax, such as decorators, cannot be handled by webpack.
You need to use babel-loader to handle compatibility.
Note: You need to exclude code in node_modules. Users do not need to worry about compatibility in third-party library code.
# 安装依赖
yarn add babel-loader @babel/core @babel/plugin-proposal-decorators -D
# 配置loader
{
test: /\.js$/,
use: [
'babel-loader',
],
exclude: /node_modules/
},
# 配置babel
# babel.config.js
module.exports = {
plugins: [['@babel/plugin-proposal-decorators', { legacy: true }]]
}
#babel文档
https://babeljs.io/setup#installation
Packaging and Release
You can use a script to record the packaging commands.
"scripts": {
"dev": "webpack serve",
"build": "webpack --mode production"
},
--mode production overrides the mode configuration in webpack.config.js. This does not affect the configuration in dev mode and can also be used to implement different configurations.
Structured project build output location
output: {
path: path.resolve(__dirname,'dist'),
filename: 'js/main.js' # 将js文件打包到js文件夹中
},
{
test: /\.jpg|png|jpeg$/,
use: [
'url-loader?limit=1024&outputPath=images',
]
},
By default, webpack does not delete old files. It only overwrites dist, so files with different names remain. This can make the output directory messy, and deleting files manually each time is tedious. Therefore, we need to configure webpack to delete them automatically before each build.
Use webpack’s clean-webpack-plugin:
npm install --save-dev clean-webpack-plugin
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const webpackConfig = {
plugins: [
new CleanWebpackPlugin(),
],
};
SourceMap
A source map is an information file that stores the location information of compressed and obfuscated code. It can be used to trace errors back to the corresponding line in the source code, making debugging easier.
Resolve issues with the default sourcemap setup.
## webpack.config.js
// 开发调试阶段建议设置为该值
devtool:'eval-source-map'
// 只展示行号不暴露源码 (在发布时可以使用这个,也可以直接省略不写)
devtool:'noresource-source-map'
Generally, @ represents the src source directory in webpack. When importing JS files, you can use @ to simplify the path.
How to configure aliases?
## webpack.config.js
resolve: {
alias:{
'@': path.join(__dirname,'src')
}
}