Introduction to the

First launched 10 years ago, Node.js has become the largest open source project in the world, with +59,000 stars on GitHub and more than 1 billion downloads. Part of the reason for the rapid growth in popularity is that Node.js allows developers to use the same language on both the client and server sides of their applications: JavaScript. Node.js is an open source and cross-platform JavaScript runtime environment designed for building scalable server-side WEB applications with high concurrency and scalability. As communities grow exponentially and proliferate, many frameworks have been created to increase productivity. In this article, we’ll explore the differences between the three most popular frameworks in Node.js: Express, Koa, and Hapi. In future articles, we’ll look at Next, Nuxt, and Nest.

  • Comparisons are based on:

    • GitHub Stars and NPM download
    • The installation
    • Basic Hello World application
    • benefits
    • disadvantages
    • performance
    • security
    • Community participation

Express

Express is a minimal and flexible Web application framework that provides a powerful set of capabilities for Web and mobile applications and behaves like a middleware to help manage servers and routing

  • star

    • Making star: + 43000
    • NPM downloads 6,881,035 per week
  • The installation

    Make sure you have Node and NPM installed

    NPM install Express --no-save // If you want to install Express temporarily instead of adding it to the dependency list, you can use NPM install Express --no-saveCopy the code
  • Hello World

    This is how to create a listening port 3000 and respond to “Hello World!” The most basic example of a fast application

    Const express = require('express')
        const app = express()
        const port = 3000
        
        app.get('/', (req, res) => res.send('Hello World! '))
        
        app.listen(port, () => console.log(`Example app listening on port ${port}! `))Copy the code
  • benefits

    • Is almost the standard for Node.js Web middleware
    • Simple, minimalist, flexible and extensible
    • Develop applications quickly
    • Fully customizable
    • Low learning curve
    • Easy integration with third-party services and middleware
    • Focus on browser, template and render integration out of the box
  • disadvantages

    While express.js is a very convenient and easy to use framework, it has some minor drawbacks that can affect the development process.

    • Organizations need to be very clear to avoid problems when maintaining code
    • As the size of the code base increases, refactoring becomes very challenging
    • A lot of manual effort is required because you need to create all the endpoints
  • performance

    Express is a basic layer of encapsulation for Web applications and inherits node.js features

    Some express performance best practices of the day include:

    • Use gzip compression
    • Do not use synchronization
    • Proper recording (for debugging, using special modules such as debugging, application activities using Winston or Bunyan)
    • Handle exceptions correctly using try-catch or promises
    • Make sure your application restarts automatically using process manager, or using systems such as Systemd or Upstar It
    • Run your application in a cluster. You can greatly improve the performance of Node.js applications by starting a cluster of processes
    • Cache the request results so that your application does not repeat operations to provide the same request over and over again
    • Use a load balancer to run multiple instances of it and distribute traffic, such as Nginx or HAProxy
    • Use reverse proxies for static resources. It can handle error pages, compression, caching, file provisioning and load balancing
A simple "Hello World" application has the following performance requests per second:Copy the code

  • security

    The Node.js vulnerability directly affects Express, so make sure you use the latest stable version of Node.js

    • View Express Best Security Practices
  • Community participation

    • Number of contributors: 220
    • Pull Requests: 821
    • Regular Express community events include Gitter, IRC Channel, Issues, Wiki, and more
Finally, Express might beNode.jsThe most popular frameworks, and many others, are built on Express.Copy the code

koa

Koa is a new Web framework, built by the same people behind Express, that aims to be a smaller, more expressive, and more robust cornerstone of web application and API development. By making use of async functions, Koa helps you discard callback functions and strongly enhances error handling. Koa does not bundle any middleware but provides an elegant set of methods to help you write server-side applications quickly and happily

  • star

    • Making star: + 25000
    • NPM weekly download: + 300K
  • The installation

    Koa requires nodev7.6.0 or higher support because of internal use of ES6 features

        npm i koa
        node my-koa-app.jsCopy the code
  • Hello World

    Create a Web service that listens on port 3000 to return ‘Hello World’

        const Koa = require('koa');
        const app = new Koa();
        
        app.use(async ctx => {
          ctx.body = 'Hello World';
        });
        
        app.listen(3000);Copy the code
  • benefits

    • Koa improves interoperability, robustness, and makes writing middleware more enjoyable.
    • There is a lot of Web API integration, but no middleware binding
    • Very lightweight, the core Koa module is only about 2K lines of code
    • Have a very good user experience
    • Better handle errors with try/catch
    • Asynchronous control flow, more readable code
  • disadvantages

    • The Koa community is relatively small
    • Incompatible with Express-style middleware (currently encountered with middleware compatible with other frameworks)
  • performance

    Koa itself is a very lightweight framework for building high-performance Web applications. The code is relatively readable and maintainable

    Of course, some performance best practices are also necessary, such as:

    • The cluster
    • Run in parallel
    • Use asynchronous apis in your code
    • Keep your code small and light
    • And using gzip compression and so on
A simple "Hello World" application has the following performance requests per second:Copy the code

  • security

    Koa has a large amount of middleware that provides a map of the corresponding functionality

  • community

    • Number of contributors: 169
    • Pull Requests: 577
    • Some discussion about KOA
Finally, Koa focuses on core middleware functionality that the design explicitly leveragesasync/ waiting makes asynchronous code more readableCopy the code

Hapi

Hapi is a framework with relatively rich basic features. Instead of spending time building infrastructure, developers are more focused on the business. Configuration driven mode, different from traditional Web server operation. It also has a unique feature, the ability to create a server on a specific IP, with similar functionality onPreHandler. You can intercept specific requests and do whatever is necessary when needed

  • star

    _ GitHub Stars: +11000

    • NPM Week download: +222,293
  • The installation

    Make sure you have Node installed

    npm install hapiCopy the code
  • Hello World

    The following example is the most basic Hello World application using HAPI:

        'use strict';
        
        const Hapi=require('hapi');
        
        // Create a service to listen on port 8000
        const server=Hapi.server({
           host:'localhost'.port:8000
        });
        
        // Add a route
        server.route({
            method:'GET'.path:'/hello'.handler:function(request,h) {
        
               return'hello world'; }});// Start the service
        const start = async function() {
           try {
               await server.start();
           }
           catch (err) {
                console.log(err);
                process.exit(1);
            }
        
           console.log('Server running at:', server.info.uri);
        };
        start();Copy the code
  • benefits

    • Provides a powerful plug-in system that allows you to quickly add new features and fix bugs
    • Extensible APIS
    • There is a deeper level of control over request processing.
    • Best choice for creating (REST) apis, providing routing, input, output validation, and caching
    • Write adaptation to each end at once
    • Detailed API references and good support for document generation
    • Use with any front-end framework such as React, Angular, and vue.js to create single-page applications
    • Configuration-based pseudo-middleware
    • Provides caching, authentication, and input validation
    • Provides a plug-in – based extension architecture
    • Provides very good enterprise plug-ins such as Joi, Yar, catbox, Boom, TV and Travelogue
  • disadvantages

    • Complex code structure
    • Plugins are not compatible, only the specified plugins such as catbox joi boom TV Good Travelogue can be used
    • Endpoints are created manually and must be tested manually
    • Refactoring is manual
  • performance

    A 2017 study of the Node framework showed that HAPI performed worst relative to other frameworks

    A simple “Hello World” application has the following performance requests per second:

  • security

    Hapi security is largely dependent on plug-ins



    Plug-in option

    • Crumb inverse (XCSRF) validation plug-in. It applies to both regular and CORS requests
    • Joi: Object schema description language and validator for JavaScript objects
    • Hapi-rbac user access control
    • Blankie is flexible enough to whitelist the mechanism
    • Cryptiles encryption library

Finally, Express is still the most popular, KOA is on the rise with its embrace of ES6, and HAPI is the first choice for large projects

Express, Koa and Hapi are all very mature frameworks today. Almost all can meet your needs, there is no best, only the most appropriate.



Code word is not easy to

My personal public number “code nongxiao Liu”, convenient to give a concern.

Not for traffic, just to make more friends like the Internet, love the front end.