Introducing some best practices at the beginning of a project can avoid a lot of complex refactoring later on. This article summarizes some best practices for building Web services using Node JS, as well as the specific steps involved.

Use the initialization scaffolding

Scaffolding helps automatically generate some code and project structure and inject some framework when initializing the code base. For a NodeJS project, there is no need to install dependencies step by step, starting with NPM init initialization.

Express command

Express is currently the most popular NodeJS Web framework. Globally install an Express-Generator to initialize the Express project.

  • Global installation command: NPM install express-generator-g

  • Create a project named Hello-Express: Express Hello-Express

Use Swagger scaffolding

When developing Web apis using NodeJS, it is highly recommended to use Swagger for API building and management, as well as providing API documentation services. The global Install Swagger command also initializes a Swagger project. The Swagger command lets you edit your API definitions and debug apis directly in real time on your browser.

Initialize the Swagger project

  • Installation command:npm install swagger -g
  • New Swagger API Project:swagger project create hello-swaggerIn the process, you are asked to choose which Web server to use, and the Express framework is automatically introduced when you select Express
  • Project Structure:
. ├ ─ ─ the README. Md ├ ─ ─ API │ ├ ─ ─ controllers │ │ ├ ─ ─ the README. Md │ │ └ ─ ─ the hello_world. Js │ ├ ─ ─ helpers │ │ └ ─ ─ the README. Md │ ├ ─ ─ │ ├─ ├─ ├─ ├─ ├─ bass exercises Package - lock. Json ├ ─ ─ package. The json └ ─ ─test└── ├─ API ├─ controllers │ ├── Java ├─ Java ├─Copy the code

Real-time editing and syntax verification

  • Start online editing:swagger project editAt this time, the system browser will be opened, in which swagger document can be directly edited and real-time grammar check can be carried out. Meanwhile, the editing changes in the browser will be written back to the code.

Online debugging API

On the right side of the image above is an API debugging tool similar to Postman.

Swagger document service

Swagger is one of the most popular API building and management tools. It is supported by libraries in various languages and frameworks, while installing Swagger UI extension for API document management and online debugging. It follows the OpenAPI standard, which defines a set of API specifications such as routing and forwarding, parameter definition and verification, etc.

  • OpenAPI specifications document swagger. IO /specificati…
  • Online API editor preview: editor.swagger. IO

Publish swagger documentation

The swagger command above is suitable for local editing, debugging, and introduction of Swagger UI middleware when publishing document services in a Production environment

app.use(SwaggerUi(swaggerExpress.runner.swagger));
Copy the code

Visit http://localhost:10010/docs/#/ to view the API documentation:

  • Online preview: petStore.swagger. IO /

  • The complete code is as follows:

SwaggerExpress.create(config, function (err, swaggerExpress) {
  if (err) {
    throw err;
  }

  // install middleware
  app.use(SwaggerUi(swaggerExpress.runner.swagger));
  swaggerExpress.register(app);

  const port = 10010;
  app.listen(port);

  if (swaggerExpress.runner.swagger.paths['/hello']) {
    console.log("Try this: \ ncurl http://127.0.0.1: ' + port + '/hello? name=Scott'); }});Copy the code

Enable ES6 JS syntax

ECMAScript is the JS language standard, and ES6 is the new JS syntax standard. An error occurs when using ES6 syntax with no other configuration. We need to introduce Babel for syntactic transformations.

import SwaggerExpress from 'swagger-express-mw'; ^^^^^^^^^^^^^^ SyntaxError: Unexpected identifier at Module._compile (internal/modules/cjs/loader.js:760:23) at Object.Module._extensions.. js (internal/modules/cjs/loader.js:827:10)Copy the code

What is the Babel

Babel is a JavaScript compiler, toolchain, primarily used to convert ECMAScript 2015+ version code into backs-compatible JavaScript syntax so that it can run in current and older versions of browsers or other environments. More documentation is available at www.babeljs.cn/docs/

How to configure it?

  • Install dependencies:
npm install -D @babel/core @babel/cli @babel/preset-env @babel/node
Copy the code
  • Create a. Babelrc file in the root directory with the following contents
{ 
  "presets": ["@babel/preset-env"]}Copy the code
  • Use the babel-node command instead of node
"scripts": {
    "start": "npm run prod"."server": "node ./app.js"  // -> "babel-node ./app.js"
}
Copy the code

How do I handle existing non-ES6 projects?

Installing an NPM Module csS-to-ES6 does some simple ES6 syntax conversions:

npm install -g cjs-to-es6
Copy the code

The resources

  • www.babeljs.cn/docs/
  • How to enable ES6 (and beyond) syntax with Node and Express:medium.freecodecamp.org/how-to-enab…

File changes monitor and automatically restart the service

Every time we modify the code, we need to restart Express to check the effect. Nodemon can help us automatically restart the service after the modification of the specified file, thus improving the development efficiency.

  • Install nodemon:npm i -D nodemon
  • Add the nodemon.json configuration file to the root directory:
{
  "exec": "npm run dev"."watch": ["src/*"."public/*"]."ext": "js, html, css, json"
}
Copy the code
  • Reference documents for more configurations: github.com/remy/nodemo…

5. Use ES Lint for code style scanning

ES Lint is a code style scanning tool, especially for team development, that helps us standardize our code style and provides integration with the IDE for code correction.

  • Install eslintnpm i -D eslint
  • Reference documents: eslint.org/docs/user-g…

Trigger the specified action when the code is submitted

There are often scenarios where continuous integration requires that we test locally before committing code. At this point we can register the “hooks” and run the tests locally before committing the code, and if the tests fail, they are not allowed to commit. So using Husky allows for this requirement:

  • Husky Documentation: github.com/typicode/hu…

Example 1: Run tests before Git push

"husky": {
    "hooks": {
      "pre-push": "npm run coverage && npm run pact:test"}},Copy the code

Example 2: Run code style checks and autocorrect before git commit

"husky": {
    "hooks": {
      "pre-commit": "npm lint"}},Copy the code

7. Enable Gzip compression to improve service response speed

Enabling Gzip compression can significantly improve the speed of accessing HTTP services, which can be easily enabled by installing compression middleware.

import compression from 'compression'; . app.use(compression());Copy the code