Build from scratch Node.js Enterprise web server (zero): static services

Time:2021-3-6

preface

In the past five years, I have worked in the development of newbie network and ant financial services. On the one hand, I have supported the business team to develop various business systems; on the other hand, I have done basic technology construction in my own technical team. In the meantime Node.js Many web systems have been developed, some of which are still vigorous, some of which have already died. In practice, the ant’s chair and the middle of Taoxi gave me a lot of inspiration, and also learned a lot from bad cases. After thinking about various cases of teams around us, our own teams and foreign teams, we found that,Build a Node.js Enterprise web server is not difficult, but must do a few key things

In the next period of time, I will focus on how to “build from scratch” Node.js Enterprise web server “as the theme, I will record what I have seen, heard, thought and thought in detail. At the end of each chapter, I will attach the source code to realize the content of this chapter. I hope it can help me to learn and understand Node.js Our friends have a clearer understanding and insight into the field of web server.

Reading tips:

  • This paper focuses on the related content of Web back-end technology, web front-end content usingJavaScript ModulesMake a demonstration.
  • This paper needs readers to have basic programming ability and basic understanding of computer network, some common terms are limited to space, no longer expand.

Prepare environment

Installation Node.js

Node.js Release versions are divided into current and lts. The former iterates a large version every six months to quickly provide new features and problem repair, while the latter takes 30 months as a large cycle to provide stable dependence for the production environment. Current Node.js The latest version of LTS is 12.18.2, which is used as the running environment in this paperDownload from official websiteAnd install.

After installation, enternode --versionCheck whether the output isv12.8.2, if consistent, the installation is successful.

In addition, interested readers can try tonvm / nvm-windowsManage multiple Node.js Version, this is not the focus of this article, will not expand.

Install yarn

Node.js It provides its own package manager NPM. By default, NPM is slow to pull package information from overseas official registry. It needs to execute the following command to set the domestic image address:

$ npm config set registry http://r.cnpmjs.org/

Through NPM, dependency packages can be installed globally or locally. When installing locally, NPM willpackage.jsonInstall the latest dependency packages and automatically generate and update thempackage-lock.jsonFile, which raises a problem: if a dependency packagepackage.jsonIf a new version with problems is released within the marked version range, our own project will also have problems.

To solve this problem, a third-party package manager is introducedyarn, install through the following command:

$ npm i -g yarn

Compared with NPM, yarn will be generated strictly according to the rulesyarn.lockLocal installation depends on the package, only add or delete the dependency orpackage.jsonThe tag version is updated only when there are incompatible changesyarn.lockThis completely eliminates the above NPM problem. Considering the stability requirement of enterprise web server, yarn is necessary.

Install docker

Generally speaking, there are two deployment options for a web server, one is traditional package deployment, the other is container image deployment. The latter is more convenient in layout than the formerKubernetesIt can do a good expansion and contraction, which is the current development trend.DockerAs the mainstream container technology must be proficient, can be used in theDownload from official websiteAnd install.

Write a static resource server

Initialization project

When the environment is ready, you can start coding. First create a new project root directory, and then enter and initialize itpackage.jsonAnd directory structure:

$MKDIR 00 static # new project root directory
$CD 00 static to enter the project root directory

$yarn init - y # initialization package.json
yarn init v1.22.4
success Saved package.json

$MKDIR SRC # new SRC directory to store core logic
$MKDIR public # create a new public directory to store static resources

$tree - L 1 # shows the current directory content structure
.
├── package.json
├── public
└── src

Express or koa?

Both express and koa are Node.js The basic framework of server.ExpressReleased in 2010, it has accumulated a large number of mature modules in the open source community with its excellent middleware mechanism. Now it is an at large level project of openjs foundation.KoaReleased in 2013, compared with express, it has a more perfect middleware mechanism and programming experience, but there is still a certain gap in the quality and quantity of the accumulation of open source community modules. Here we compare several common modules

Module name Function introduction Express / Koa Star Contributers Used by Latest submission time
passport Authentication login Express 17.7k 33 385k 2020-06-10
koa-passport Authentication login Koa 737 21 4.7k 2019-07-13
connect-redis Session storage Express 2.3k 51 26.3k 2020-07-10
koa-redis Session storage Koa 310 13 2.7k 2020-01-16
helmet network security Express 7.2k 25 136.4k 2020-07-11
koa-helmet network security Koa 546 24 4.1k 2020-06-03

The above table is compiled fromGithubData as of July 20, 2020.

Compared with koa module, express module generally has a higher level in star, contributors and used by. At the same time, express module contributors are more enthusiastic about maintenance and update. Although koa has been sought after in China, express is a more robust choice under more comprehensive consideration. Execute the following command to install in the project root directory:

$yarn address express ා install express locally
# ...
info Direct dependencies
└─ [email protected]
# ...

$tree - L 1 # shows the current directory content structure
.
├── node_modules
├── package.json
├── public
├── src
└── yarn.lock

Static service

Now we can start to write application logic. In this chapter, we will build a static resource server topublicThe directory is a static resource directory

// src/server.js
const express = require('express');
const { resolve } = require('path');
const { promisify } = require('util');

const server = express();
const port = parseInt(process.env.PORT || '9000');
const publicDir = resolve('public');

async function bootstrap() {
  server.use(express.static(publicDir));
  await promisify(server.listen.bind(server, port))();
  console.log(`> Started on port ${port}`);
}

bootstrap();
<!-- public/index.html -->
<html>
  <head>
    <meta charset="utf-8" />
  </head>
  <body>
    <h1>It works!</h1>
  </body>
</html>
$ tree -L 2 -I node_ Modules # display except node_ Directory content structure outside modules
.
├── package.json
├── public
│   └── index.html
├── src
│   └── server.js
└── yarn.lock

After the logic is writtenpackage.jsonSet the startup script in:

{
  "name": "00-static",
  "version": "1.0.0",
-  "main": "index.js",
+  "scripts": {
+    "start": "node src/server.js"
+  },
  "license": "MIT",
  "dependencies": {
    "express": "^4.17.1"
  }
}

Then you can start the app:

$ yarn start
> Started on port 9000

visithttp://localhost:9000/You can seeindex.htmlContent:

Build from scratch Node.js  Enterprise web server (zero): static services

Using containers

Next, the static resource server is containerized through docker, and the following configuration files are created:

# Dockerfile
FROM node:12.18.2-slim

WORKDIR /usr/app/00-static
COPY . .
RUN yarn

EXPOSE 9000
CMD yarn start
# .dockerignore
node_modules
$tree - L 1 - a ා shows all the directory content structure at the beginning of
.
├── .dockerignore
├── Dockerfile
├── node_modules
├── package.json
├── public
├── src
└── yarn.lock

Then build the image and start the container:

$# build a container image, named 00 static and labeled 1.0.0
$ docker build -t 00-static:1.0.0 .
# ...
Successfully tagged 00-static:1.0.0

$00 in mirror image- static:1.0.0  Run the container, named 00 static
$ docker run -p 9090:9000 -d --name 00-static 00-static:1.0.0

$docker logs 00 static # view the logs of the 00 static container
> Started on port 9000

$docker stats 00 static # view the status of the 00 static container
CONTAINER ID        NAME                CPU %               MEM USAGE / LIMIT     MEM %               NET I/O             BLOCK I/O           PIDS
43c451232fa5        00-static           0.03%               37.41MiB / 1.945GiB   1.88%               8.52kB / 3.35kB     0B / 0B             24

visithttp://localhost:9090/You can see it as beforeindex.htmlContent:

Build from scratch Node.js  Enterprise web server (zero): static services

Source code of this chapter

host1-tech/nodejs-server-examples – 00-static

Read more

Build from scratch Node.js Enterprise web server (zero): static services
Build from scratch Node.js Enterprise web server (1): interface and layering
Build from scratch Node.js Enterprise web server (2): Verification
Build from scratch Node.js Enterprise web server (3): Middleware
Build from scratch Node.js Enterprise web server (4): exception handling
Build from scratch Node.js Enterprise web server (5): database access
Build from scratch Node.js Enterprise web server (6): session
Build from scratch Node.js Enterprise web server (7): authentication login
Build from scratch Node.js Enterprise web server (8): network security
Build from scratch Node.js Enterprise web server (9): configuration items
Build from scratch Node.js Enterprise web server (x): log
Build from scratch Node.js Enterprise web server (11): timed tasks
Build from scratch Node.js Enterprise web server (12): remote call
Build from scratch Node.js Enterprise web server (XIII): breakpoint debugging and performance analysis
Build from scratch Node.js Enterprise web server (14): automated testing
Build from scratch Node.js Enterprise web server (XV): summary and Prospect