Over the past six months, we have summarized 10 experiences using node. js. Over the past six months

Source: Internet
Author: User
Tags cert verification

Over the past six months, we have summarized 10 experiences using node. js. Over the past six months

Let alone house prices, traffic jams, and smog... Let's talk about my experience using Node. js over the past six months... They are all problems encountered at work and blood lessons ..

1. Exact version number

"You must be accurate to the specific version number! Use * to roll directly, ^ and ~ None !", When we first arrived at the company in the morning, our server's head was full of bloodshot eyes (it was estimated that we slept some time in the early morning) and complained to me: "Mom, the code package we wrote earlier. the version in json is different from the version running on the server. ." Thousands of characters are omitted here...

Okay. First, I face myself. In the past, only * is used *... Most of the time there is no need to write the dead version number, using ^ and ~ Or. Blind scan:

Semver
Version Management in node. js

2. Test

Be sure to write test cases. Take me for example. The part I take charge of contains the filtering part (use the regular expression to filter the text and extract useful text ). With the test case, after each modification to the filtering rule, it is appropriate under npm test. Select the testing modules, mocha, shoshould, tape, tap, and supertest as per your preferences.

Run the command locally. After the test is successful, the file is uploaded to the server. After several code changes (just a few simple changes), I thought how the problem could occur. As a result, I got down after I restarted the server .. Nima missing brackets or something .. You can also use editor plug-ins such as jslint or jshint to detect low-level syntax errors.

Back up the server code. Currently, I am using the following method: At first, there were two identical projects on the server (different git libraries and file names), one being running and the other being used as a backup. When code changes occur, go to git pull under the backup project, stop the running program, and start the backup program. If the program fails for a period of time, that is, the project is considered as the master project, and the other project is considered as the slave project. When there is another change, repeat the above steps to switch back and forth between the master and slave. If the program fails, you can switch back to a more stable backup.

3. Use debug

Debugging is inevitable for writing programs. Many people prefer to use the omnipotent console. log (), including me .. Personally, after I use console. log () to complete the call, either delete or comment out. It may be used again after it is deleted. It is ugly to comment it out. Use the debug module. Node-inspector has never been used for the time being and is not evaluated.

4. Keep code concise

Trying to do more things with less code is also a test of your ability. This includes correct indentation, proper variable names, and clear code organization structures .. The code is streamlined and beautiful. When something goes wrong, it will be faster to look back at the error. It will take a few hours to figure out what a mess of code has done.

If the team does not use CoffeeScript, do not use it. First, others cannot understand your code to help you correct the error. Second, the number of lines displayed after an error is different from the number of lines in the coffee code... You can use your own open-source projects.

5. consult more and keep thinking independently

At the beginning of my work, I was confused, including technical and business logic problems. I often consulted the team's experts. Then I will try to make up for technical deficiencies and clarify the business logic. Later, I wanted to design an api according to PM's requirements, taking into account the user's needs (in the case of multiple clients), the client's needs and behaviors, the Database Design (how to store less redundancy, less queries, easy expansion, easy modification, and poor queries) takes into account more than a week, and almost crashes... Although I have discussed it with the header many times, it always gives me logic and does not tell me the method. Later, I finally found a good solution .. He also told me later that he wanted me to keep thinking independently to solve the problem so that I could improve ..

6. Use the existing library

At present, there are nearly third-party modules on npm. Theoretically, all the modules you want to use can be found on npm. Of course, there are many excellent modules on npm, and the documents are comprehensive, it is also very convenient to use and usually meets the needs. If you find that a module can meet most of the requirements, you can improve the functionality or have bugs. You can go to github to raise the pr. If you find that the module cannot be found, you can create and share npm publish with you on npm. Of course, if you find that some modules that implement a certain function are shit, you can also publish them without shit.

7. Keep it simple

If you want to display a pie chart, use HTML5 canvas or CSS3. You do not need to use the C ++ canvas library to draw an image, "The library that the download depends on is 400 + MB," said the first.

8. Good documentation

Good documentation is the most important channel for the client to communicate with the server team. The document is clearly written. If an error occurs in the client request, you can view the document first (for example, what is the meaning of each error code), instead of looking for someone on the server to discuss each problem. PS: some http request examples should be written in curl as much as possible, rather than js objects. You may be familiar with it, but clients do not understand js.

9. Configuration File

Create a configuration file under each project directory, such as config. js/config. json. Instead of writing it to the code. For example:

{
"App": 3000,
"Mongo ":{
"Host": "localhost ",
Port: 27017
},
"Redis ":{
"Host": "localhost ",
Port: 6379
}
...
}
10. Use pm2

Using pm2 and other process management tools is very convenient, and the crash can be automatically restarted even if the process fails. Forever is not used for evaluation .. There are also grunt, which has never been used, and we will not comment on it.


Nodejs can be used to implement a simple interface server.

Var http = require ('http'); var mysql = require ('mysql'); var connection = mysql. createConnection ({host: 'localhost', user: 'me', password: 'secret',}); // start your mysql connection. connect (); var server = http. createServer (function (req, res) {// if you send a GET request to 127.0.0.1: 1337/test? Var url_info = require ('url') If a = 1 & B = 2 '). parse (req. url, true); // check whether requestif (url_info.pathname = '/test') for/test {// use url encode for query, in this way, you can use post to send var post_data = require ('querystring '). stringify (url_info.query); // optionvar post_options of post = {host: 'localhost', port: 1337, path: '/response_logic', method: 'post', headers: {'content-type': 'application/x-www-form-urlencoded ', 'content-length': post_data.length}; // issue the postvar request_made = http. request (post_options, function (response_received) {var buf_list = new Array (); response_received.on ('data', function (data) {buf_list.push (data );}); response_received.on ('end', function () {var response_body = Buffer. concat (buf_list); res. end (response_body); connection. query ('insert ......... ', function (err, rows, fields) {// process your result}) ;}); // send the post's datare ...... remaining full text>

What improvements have been made to Nodejs 010?

2013.04.11, Version 0.10.4 (Stable)

* Uv: Upgrade to 0.10.4

* Npm: Upgrade to 1.2.18

* V8: Avoid excessive memory growth in JSON. parse (fedorindutny)

* Child_process, cluster: fix O (n * m) scan of cmd string (Ben Noordhuis)

* Net: fix socket. bytesWritten Buffers support (Fedor Indutny)

* Buffer: fix offset checks (invalid ukasz Walukiewicz)

* Stream: call write cb before finish event (isaacs)

* Http: Support write (data, 'hex') (isaacs)

* Crypto: dh secret shocould be left-padded (Fedor Indutny)

* Process: expose NODE_MODULE_VERSION in process. versions (Rod vswitches)

* Crypto: fix constructor call in crypto streams (Andreas Madsen)

* Net: account for encoding in. byteLength (fedorindutny)

* Net: fix buffer iteration in bytesWritten (Fedor Indutny)

* Crypto: zero is not an error if writing 0 bytes (Fedor Indutny)

* Tls: Re-enable check of CN-ID in cert verification (Tobias müllerleile)

2013.04.03, Version 0.10.3 (Stable), d4982f6f5e4a9a703379489a553b8d782997ea43

* Npm: Upgrade to 1.2.17

* Child_process: acknowledge sent handles (Fedor Indutny)

* Etw: update prototypes to match dtrace provider (Timothy J Fontaine)

* Dtrace: pass more arguments to probes (Dave Pacheco)

* Build: allow building with dtrace on osx (Dave Pacheco)

* Http: Remove legacy ECONNRESET workaround code (isaacs)

* Http: Ensure socket cleanup on client response end (isaacs)

* Tls: Destroy socket when encrypted side closes (isaacs)

* Repl: isSyntaxError () catches "strict mode" ...... the remaining full text >>>
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.