Nodejs experience talk

foreword

Here I mainly talk about the pits that I used to develop with Nodejs before. I only say that the pits are not filled in, that is to play hooligans naked. There are a lot of explanations and methods of filling the pits in the text.

PS: To be honest, Nodejs has quite a lot of pits; but it is easy to get started, and there are many extension packages, which make your development very easy.

1. The code is simplified

Try to use simplified code as much as possible. Nodejs code processing speed is extremely slow, not as good as other mainstream languages, even not as good as python . Using simplified code is also an improvement and test of one's own abilities. When we were working on the Cartier Mall project, the other engineer requested that the same variable cannot appear three times in the same function (only counted as one in the loop). When the code is simplified, it will become beautiful, it will be easier to find problems, and it will be convenient for later engineers to take over.

It is not recommended to apply other frameworks in Nodejs code, such as coffeescript, Node and Coffee will report different errors.

2. Exact version number

It is estimated that many people have stepped on this pit, and the development environment is inconsistent with the actual environment. When a colleague develops a module, the local joint debugging is no problem, but after reaching the server side, it cannot be started at all. After searching around, I finally found that my colleague is using the fossil version of Node for local development. It is such a small negligence that we waste it. I spent the morning looking for the reason.

Add some knowledge of Node version management :

*                       // Any version 
1.1.0                   // Specified version 
~1.1.0                  // >=1.1.0 && < 1.2.0 
^1.1.0                  // >=1.1.0 && < 2.0.0

 3. Unit testing

Be sure to write a unit test case, try to run it locally, and upload it to the server after the test is successful. After modifying the code a few times (simple lines), I thought there might be a problem, but as soon as the service is restarted, it hangs, and there may be less brackets and so on. of.

Mocha is my longest-used unit testing tool:

basic concept:

describe() test blocks, which can be nested in multiple layers.

it() test case, a test block can contain multiple test cases.

Test hook:

before() is executed before all test cases in this block are executed.

after() is executed after all test cases in this block are executed.

beforeEach() is executed before each test case in this block .

afterEach() is executed after each test case in this block .

Affirmation:

chai ; Mocha itself does not assert, chai can be used as its assertion library. chai-as-promise This library supports promises.

Use case management:

only() Both test blocks and test cases support the only method, which only runs the decorated test block or case.

skip() Both test blocks and test cases support the skip method, which will skip the decorated test block or case.

When only is used with skip, only ignores skip.

Asynchronous call:

done(), called after the test method is completed asynchronously. There can only be one done() in an it test instance.

example:

var assert = require('chai').assert;

function add() {
    return Array.prototype.slice.call(arguments).reduce(function (prev, curr) {
        return prev + curr;
    }, 0);
}

describe('add()', function () {
    var tests = [
        { args: [1, 2], expected: 3 },
        { args: [1, 2, 3], expected: 6 }
    ];

    tests.forEach(function (test) {
        it('test adds ' + test.args.length + ' args', function () {
            var res = add.apply(null, test.args);
            assert.equal(res, test.expected);
        });
    });
});

 4.debug

Debugging cannot be avoided in development. Many people like to use console.log() for debugging. This is really useful, but how to deal with console.log() after debugging has become a difficult problem. Comments, there will be a lot more Useless code, delete it, it may be used later.

Here, I recommend using the debug module as an example:

var debug = require('debug')('myapp:main');
debug( 'The current time is %s' , new Date());

Turn on debug mode (input on cmd): set debug = myapp:main

Then enter the file to be executed: node app.js

Returns: myapp:main The current time is 2018-05-03 18:25:30

Turn off debug mode: set debug = null

5. Configuration file writing

A configuration file, such as config.js , must be established under each project , instead of being written in the program. Remember that the person who takes over your work is someone who does not understand your programming logic, so you have to tell the other party what Whether it can be matched or not, you will be very troublesome later.

Configuration file example:

{
   "app": 3000,
   "mongo": {
      "host": "localhost",
      "port": 27017
    },
    "redis": {
       "host": "localhost",
       "port": 6379
    }
  ...
}

 6. Avoid synchronous code

A distinguishing feature of Nodejs: it is designed from top to bottom for asynchrony . There are synchronous and asynchronous versions of file operations, and even if logic is used to control synchronous methods, it is still possible to inadvertently use blocking external function libraries. Doing so has a huge impact on performance.

// Good way of writing 
fs.writeFile('message.txt','Hello Node', function (err) {
 console.log("It's saved and the server remains responsive!");
});

// Bad writing style (affecting performance) 
fs.writeFileSync('message.txt', 'Hello Node' );
console.log("It's saved, but you just blocked ALL requests!");

7. Don’t let static resources use Nodejs

For static resources such as css and images, use standard webserver instead of Nodejs. We are using a CDN to store static resources.

Benefits :

  1) Reduce the load of nodejs server.

  2) CDN allows static content to be delivered on servers closer to users, reducing waiting time.

8. Rendering on the client side

Let's compare the difference between rendering on the client side and rendering on the server side:

server-side rendering

<!DOCTYPE html>
<html>
    <head>
        <title>服务端渲染</title>
    </head>
    <body>
         <div>
              py1988!
         </div>
    </body>
</html>            

client-side rendering

<!DOCTYPE html>
<html>
    <head>
        <title>客户端渲染</title>
    </head>
    <body>
         <div>
              <%= name %>!
         </div>
    </body>
</html>  

The javascript text can be cached in the browser or locally. After all initial loading, the only thing to send to the client is json, which is the most effective and greatly reduces the load of the Nodejs server.

9. Parallelization

Try to parallelize all blocking operations, this will reduce the waiting time of blocking operations, in order to keep callbacks and error handling clean, we need to use some monitoring tools.

10. Try to use binary modules

Use binary modules instead of javascript modules (as much as possible); this will improve performance a lot.

var crypto = require('crypto');
var hash = crypto.createHmac("sha1",key).update(signatureBase).digest("base64");

Special: use V8 javascript instead of client library

Many javascript libraries were created to be used on browsers: some browsers support functions like forEach, map and reduce, but some browsers don't.

The V8 javascript engine supports Node.js implementing ECMAScript as specified in ECMA-262 Fifth Edition. Replacing the client-side library directly with standard V8 JavaScript functions, you will find a significant performance improvement.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325529313&siteId=291194637