Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money.

preface

This time sorted out some of the knowledge points encountered in writing node ah, check the gaps, in order to make their growth more stable oh!

Recently, I have participated in the simulation competition of blue Bridge Cup web direction. Let’s catch a wave of friends who are also participating

feeling

Encountered a lot of modular writing method, before their own writing really this aspect is not very attention, because they write their own look, of course how comfortable how, it reminds me to be a little more elegant ~, but indeed, so write after a batch of sweet ~

Some tool knowledge

Koa initialization

1.1 Global scaffolding installation tools

cnpm install -g koa-generator 
# or 
yarn global add koa-generator 
Copy the code

1.2 Go to the project folder directory and run the generate command

# koA2 + project name koA2 manager-serverCopy the code

1.3 Installation Dependencies

npm install 
# or
cnpm install
# or
yarn
Copy the code

Deploy Koa projects and start, shut down, and restart automatically using PM2

1. Global installation

npm install -g pm2
Copy the code

2. Start the project

Go to the project directory and start the project using PM2. Note here: when launching a single file (app.js is the name of the project file)

Pm2 start app.js #Copy the code

But in KOA2 you need to start like this:

Pm2 start. /bin/ WWW # Start koA2 projectCopy the code

3. The PM2 automatically restarts

Stop the PM2 service first and wear a watch when you get up

pm2 start ./bin/www --watch
Copy the code

4. Pm2 related commands (WWW is the project name)

Pm2 start # pm2 restart WWW # pm2 stop WWW # delete WWW #Copy the code

The following are the two utility functions encapsulated

Use log4JS to encapsulate log output

Start by creating your log4j.js file in the utils folder and importing log4js

    const log4js = require('log4js')
Copy the code

The following are the levels defined. Up to now, only three levels have been used, but there are many definitions in the tutorial, which may be that I have not used them.

const levels = {
    'trace':log4js.levels.TRACE,
    'debug':log4js.levels.DEBUG,
    'info':log4js.levels.INFO,
    'warn':log4js.levels.WARN,
    'error':log4js.levels.ERROR,
    'fatal':log4js.levels.FATAL,
}
Copy the code

The next step is to add some configuration using log4js.configure.

Appenders: additional device

appenders:{ console:{ type: 'console' }, info:{ type:'file', filename:'logs/all-logs.log' }, error:{ type: 'dateFile, filename:' logs/log ', the pattern: '- dd yyyy - MM. The log, alwaysIncludePattern: true / / set the file name is filename + pattern}},Copy the code

It can be seen that in the append, the output of info and error logs are saved in a file, which is convenient for us to refer to and record. The error logs are recorded with the date of the day, and the INFO logs are stored in a file

Categories: Output type

    categories:{
        default: { appenders: ['console'], level: 'debug' },
        info:{
            appenders: ['info','console'],
            level: 'info'
        },
        error:{
            appenders: ['error','console'],
            level: 'error'
        }
    }
Copy the code

The default output level is debug, which we use to print things

Note that we can only add what is defined in appenders.

Here are three functions: debug, error, info. Export them for easy use:

exports.debug = (content) =>{ let logger = log4js.getLogger() logger.level = levels.debug logger.debug(content) } exports.error = (content) =>{ let logger = log4js.getLogger('error') logger.level = levels.error logger.error(content) }  exports.info = (content) =>{ let logger = log4js.getLogger('info') logger.level = levels.info logger.info(content) }Copy the code

Then we go to app.js and replace the original log output with what we wrote. The location is about logger and error. Just replace it with our info and error.

Remember to introduce log4js first!

Encapsulating tool function

Utility functions currently have the following functions:

  • Returns a status code on success or failure
  • Preliminary paging structure

Let’s define our status code:

Const CODE = {SUCCESS:200, PARAM_ERROR:10001, // Parameter error USER_ACCOUNT_ERROR:20001, // Account or password error USER_LOGIN_ERROR:30001, BUSINESS_ERROR:40001, // Service request failed AUTH_ERROR:50001, // Authentication failed or TOKEN expired}Copy the code

The next one will be 60001. Don’t guess.

Module.exports exports all of the following functions:

   success(data='',msg='',code=CODE.SUCCESS){
        log4js.debug(data);
        return{
            code,data,msg
        }
    },
    fail(msg='',code=CODE.ERROR){
        log4js.debug(msg);
        return{
            code,data,msg
        }
    }
Copy the code

I specially introduced the function of the previous log output here, so that printing it here is convenient for us to debug. If it is successful, we should focus on the returned data; if it fails, we definitely do not return the data. We should focus on the MSG at that time to find out the cause of failure.

    pager({pageNum=1,pageSize=10}){
        pageNum*=1;
        pageSize*=1;
        const skipIndex = (pageNum-1)*pageSize;
        return{
            page:{
                pageNum,
                pageSize
            },
            skipIndex
        }
    },
Copy the code

This function is a page-structure function. By default, a page is ten data, and arithmetic is used to convert pageNum and pageSize to number.

The skipIndex is the index we use to look up the data on a page. If we are on page 3, (3-1) * 10=20, so our next index should start at 20.

Write in the last

1024 will arrive soon, wish the programmer of the world recently bug all a little less, hair all a little more!

Point a “like”, work together to refueling ♥