Node.js application development introduction

Node.js is an open source and cross-platform JavaScript runtime environment

Run the V8 JavaScript engine (the core of Google Chrome) outside of the browser to improve performance using techniques such as event-driven, non-blocking, and asynchronous input/output models

Node.js is a server-side, non-blocking I/O, event-driven JavaScript runtime environment

Hd web disk XZ:Build tens of millions of highly available enterprise Node.js applications

Node. Js advantages and disadvantages

Advantages:

The performance in high-concurrency scenarios is better for I/ O-intensive applications. The CPU usage of applications is still low at the operating limit, and most of the applications are reading and writing data from and to I/O disks

Because Nodejs is single-threaded, it has the following disadvantages:

It is not suitable for CPU-intensive applications. Only single-core cpus are supported, which cannot make full use of CPUS. The reliability is low

Build ten million high availability enterprise node.js application actual combat – Node.js memory management

Node.js memory management Unlike platforms like PHP, node.js applications are always running processes. While this mechanism has many advantages, such as the ability to configure database connection information so that all requests can reuse the connection information only once, unfortunately, it also has drawbacks. But first, let’s take a look at the basics of Node.js. V8 memory management mode A running program is usually represented by allocating a portion of memory. This part of the space is called a Resident Set. V8’s memory management model is somewhat similar to that of the Java Virtual Machine (JVM), which divides memory into segments:

Stack: includes all the value types (primitives, such as integers and booleans) that carry Pointers to the objects on the heap, as well as Pointers that define the flow of program control. In node.js, the current memoryUsage can be easily queried using process.memoryUsage, as shown in the following example:

var util = require('util');
console.log(util.inspect(process.memoryUsage));
Copy the code

This will produce the following result on the console:

{ 
    rss: 4935680,
    heapTotal: 1826816,
    heapUsed: 650472
}
Copy the code

As we’ve seen, garbage collection is a very complex process, and even if the code doesn’t have a problem, it can lead to memory leaks. Out of the box features provided by V8 (and chrome developer Tools) can help us locate the source of the problem, which can be very helpful if you build this mechanism into your application to find and fix problems.

Of course, if you ask me how to fix the above code, it is very simple, just add the line theThing = null at the end of the function; Can.

Build ten million high availability enterprise node.js application practice-log management

The installationlog4jsThe module

npm i log4js -S
Copy the code


log4jsOfficial simple example

Create mi-log/demo.js in the middleware/ directory and post the official sample code:

var log4js = require('log4js');
var logger = log4js.getLogger();
logger.level = 'debug';
logger.debug("Some debug messages");

Copy the code


Run it in /middleware/mi-log/ :

cd ./middleware/mi-log/ && node demo.js
Copy the code


You can see the following output on the terminal:

[2017-10-24 15:45:30.770] [DEBUG] default-some DEBUG messagesCopy the code

A text log with the date, time, log level, and string passed in when the debug method is called. Realize simple terminal log output.


log4jsOfficial complex example

Replace the code in mi-log/demo.js as follows:

const log4js = require('log4js');
log4js.configure({
  appenders: { cheese: { type: 'file'.filename: 'cheese.log'}},categories: { default: { appenders: ['cheese'].level: 'error'}}});const logger = log4js.getLogger('cheese');
logger.trace('Entering cheese testing');
logger.debug('Got cheese.');
logger.info('Cheese is Gouda.');
logger.warn('Cheese is quite smelly.');
logger.error('Cheese is too ripe! ');
logger.fatal('Cheese was breeding ground for listeria.');
Copy the code


Run again in /middleware/mi-log/ :

node demo.js
Copy the code


After this command is executed, a cheques. log file is generated in the current directory. There are two logs in the file and they record information of the error level or higher.

[2017-10-24 15:51:30.770] [ERROR] Cheese - Cheese is too ripe! [2017-10-24 15:51:30.774] [FATAL] Cheese-cheese was breeding ground for listeria.Copy the code

Note: The location where the log files are generated is the location of the current startup environment.


If you analyze the code above, the configure function configures the basic log information

{
  /** * Specifies the type of the log to be recorded
  appenders: { cheese: { type: 'file'.filename: 'cheese.log'}},/** * Specifies the default configuration item of the log * If not specified in log4js.getLogger, the default configuration item of the log is cheese * specifies the content of the log to be error or higher information */
  categories: { default: { appenders: ['cheese'].level: 'error'}}}Copy the code

Rewrite to log middleware

Create /mi-log/logger.js and add the following code:

const log4js = require('log4js');
module.exports = ( options ) = > {
  return async (ctx, next) => {
    const start = Date.now()
    log4js.configure({
      appenders: { cheese: { type: 'file'.filename: 'cheese.log'}},categories: { default: { appenders: ['cheese'].level: 'info'}}});const logger = log4js.getLogger('cheese');
    await next()
    const end = Date.now()
    const responseTime = end - start;
    logger.info('response time is${responseTime/1000}s`); }}Copy the code


Create /mi-log/index.js and add the following code:

const logger = require("./logger")
module.exports = () = > {
   return logger()
}
Copy the code


Modify the middleware/index.js file and add the log middleware registry as follows:

const path = require('path')
const bodyParser = require('koa-bodyparser')
const nunjucks = require('koa-nunjucks-2')
const staticFiles = require('koa-static')

const miSend = require('./mi-send')
// Introduce logging middleware
const miLog = require('./mi-log')
module.exports = (app) = > {
  // Register middleware
  app.use(miLog())

  app.use(staticFiles(path.resolve(__dirname, ".. /public")))
  app.use(nunjucks({
    ext: 'html'.path: path.join(__dirname, '.. /views'),
    nunjucksConfig: {
      trimBlocks: true}})); app.use(bodyParser()) app.use(miSend()) }Copy the code

Total heap-heapUsed Total heap-heapUsed Total heap-heapUsed