The pitfalls on nodejs in those years (1)

Source: Internet
Author: User

I wrote node. js myself for a while. I had many pitfalls (and most of them I buried myself), and I have seen many pitfalls that others have stepped on. The reason is actually very simple, either the knowledge point is not deeply understood, or the coding habit is not good. In response to the call of Peng chunda, I plan to sort out these pitfalls and give myself a memo. I also hope to help you.

1. Callback

Event Callback is a very common application scenario of nodejs. Let's take a look at the following code to see if there are any problems?

Get (Params, function (ERR, data) {If (ERR) {callback (ERR);} // var ROW = data [0];});

See it. Yes, that is, when the err exists, after callback, the following code will be executed. At this time, we often cannot control what the data value is. If undefined is returned for data at this time, the program will surely report an error. Of course, the solution is very simple, that is, add a return before callback:

Get (Params, function (ERR, data) {If (ERR) {return callback (ERR);} // var ROW = data [0];});

This knowledge point is not very difficult, but it is often a very easy mistake for beginners. Even students who have been writing code for a long time may occasionally make this low-level mistake.

Here is a more concealed one:

db.get(key, function(err, data) {  if (err) {    return callback(err);  }  try {    callback(null, JSON.parse(data.toString()))  } catch(e) {    callback(e);  }});

It seems that there is no problem. Hey, reveal the answer. Yes, it's called back twice. Callback (null, error) once, callback (E), for example:

 

function asyncfun(data, callback) {  try {    callback(null, JSON.parse(data.toString()));  } catch (e) {    callback(e);  }}var json = {'a': 'b'};var jsonstr = JSON.stringify(json);var d = new Buffer(jsonstr);asyncfun(d, function(err, data) {  console.log(err);  throw new Error('new Error');});

Running result:

null[Error: new Error]

This is definitely a pitfall in a big project, and it takes a long time to correct errors.

 

2. Buffer

Still old rules, first look at the Code:

VaR DATA = ""; Res. on ('data', function (chunk) {Data + = chunk ;}). on ("end", function () {// transcode data });

This code is correct when Chunk is an ascii code or when the data volume is small. However, if your data is in a large number of Chinese characters, congratulations. garbled characters may occur when you get shot. The reason is that the splicing of two chunks (buffer objects) is not normal, which is equivalent to buffer. tostring () + buffer. tostring (). If the buffer is not complete, the string after the tostring is output is faulty (for example, a text is truncated ). For more information, see this article: http://cnodejs.org/topic/4faf65852e8fb5bc65113403

3. Deep nesting

Many people who have just started writing node. JS Code have written such code more or less because their thinking is still in sync:

func1(err, function(err1, data1) {  func2(err1, function(err2, data2) {    func3(err3, function(err3, data3) {      func4(err4, function(err4, data4) {        .......      })    })  })})

Let alone whether such code is easy to maintain. It looks ugly and the code is "skewed. I was not afraid of everyone's ridicule. I wrote such a code when I first wrote it, for this reason, I wrote an article "How to synchronize node. js operations" to explain how to solve this problem. However, from the source, we should try to avoid using this synchronous method, because the advantage of nodejs is that it is asynchronous, and it is absolutely thankless to achieve synchronization.

 

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.