用Node.js时不应该做的7件事

Seven Things You Should Stop Doing with Node.js

Inspired by 5 Things You Should Stop Doing With jQuery by Burke Holland, I decided to open a discussion and highlight seven things you should immediately stop doing with Node.js:

受Burk Hollad的博文《用jQuery时不应该做的5件事》启发,我决定做一个讨论并强调7点用Node.js时不应该做的事情:

  1. Stop using callbacks 不要使用回调
  2. Stop using * for versions 不要使用*版本
  3. Stop using console.log for debugging 不要使用console.log做调试
  4. Stop using GET and POST for everything 不用使用GET和POST
  5. Stop using semicolons 不用使用分号
  6. Stop using comma-first style 不要使用逗号开头的风格
  7. Stop limiting your connections with default maxSockets value 不要用缺省maxSockets值限制连接数

Stop Using Callbacks in Node.js 不要在Node.js中使用回调

Callbacks are the bread and butter (or the meat and veggies for paleo lifestyle readers) of the JavaScript/Node.js language and the main pattern. However, you should stop using callbacks for nesting code of multiple methods unless you want to end up with the Callback Hell.

回调函数是JavaScript/Node.js语言和主要模式的面包和黄油(或者对于古老生活方式的读者来说,是肉类和蔬菜)。然而,除非你想以陷入回调地狱告终,你就不应该在多个方法的嵌套代码中使用回调函数。

Async is for the win. Particularly its series() and waterfall() methods.

To illustrate the drastic difference, here is an example in which we perform multiple operations with callbacks to find a user, then find posts that belong to the user:

为了演示这戏剧性的不同之处,下面是一个我们通过多个回调操作寻找一名用户的例子,然后找到该用户的发帖纪录:


codeA(function(a){
  codeB(function(b){
    codeC(function(c){
      codeD(function(d){
        // Final callback code        
      })
    })
  })
})

The series example:


async.series([
  function(callback){
    // code a
    callback(null, 'a')
  },
  function(callback){
    // code b
    callback(null, 'b')
  },
  function(callback){
    // code c
    callback(null, 'c')
  },
  function(callback){
    // code d
    callback(null, 'd')
  }],
  // optional callback
  function(err, results){
    // results is ['a', 'b', 'c', 'd']
    // final callback code
  }
)

The waterfall example:


async.waterfall([
  function(callback){
    // code a
    callback(null, 'a', 'b')
  },
  function(arg1, arg2, callback){
    // arg1 is equals 'a' and arg2 is 'b'
    // Code c
    callback(null, 'c')
  },
  function(arg1, callback){      
    // arg1 is 'c'
    // code d
    callback(null, 'd');
  }], function (err, result) {
   // result is 'd'    
  }
)

Stop Using WildCard * for Versions with Node.js 不要在Node.js版本使用通配符*

The wildcard * instead of the version number in package.json seems like a good idea — an automatic update in the near future. Wrong! You should use exact version numbers to prevent any third-party module changes from breaking your app and waking up you in the middle of the night wondering what went south.

This is especially true if you don’t commit your node_modules folder or don’t useshrinkwrap.

 

A bad example from HackHall package.json circa summer 2013:


{
    "name": "hackhall",
    "version": "0.0.1",
    "private": true,
    "main": "server",
    "scripts": {
        "start": "node server"
    },
    "dependencies": {
        "express": ">=2.2.0",
        "jade": "*",
        "mongodb": "*",
        "mongoose":"",
        "oauth":"*"
    },
    "devDependencies":{
        "mocha": "",
        "superagent":""
    },
    "engines": {
      "node": ">=0.6"
    }
}

A good example from the Practical Node.js book [2014, Apress]:


{
  "name": "blog-express",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js",
    "test": "mocha test"
  },
  "dependencies": {
    "express": "3.4.5",
    "jade": "0.35.0",
    "mongoskin": "~0.6.1",
    "stylus": "~0.40.3",
    "mocha": "1.16.2",
    "superagent": "0.15.7",
    "expect.js": "0.2.0"
  }
}

If you don’t want to go to NPM website every time to check the version, you can use$ npm install package_name --save which will save the version number in the package.json.

If the module is installed already you can:

  • Type $ npm ls
  • Open the package folder and copy the version number form package.json

Stop Using console.log for Debugging Node.js Apps 不要使用console.log调试Node.js应用

What is the best debugger? Right, it’s console.log! It’s fast, non-interrupting and gives us any information we ask for (like the value of a pesky variable). Then why should you stop using it? Because real debuggers like Node Inspector provide not only the value of a variable you just hard-coded, but also give you a dynamic ability to look around, inside the process.

For example, I might have a condition (where resubmit is a boolean) that is not acting right:


if (resubmit && post.published && user.plan.paid && post.isVisible) {
  // code A
} else {
 // code B
}

With console.log I can type only console.log(resubmit), orconsole.log(resubmit, ...) some other variables. But, with debugger, I can poke around and print anything I have access to in that scope. If that is not enough, I’ll step over or step in the Code A or B as show in the example.

Stop Using GET and POST for Everything in Node.js servers 不用在Node.js服务器上使用GET和POST

Stop using GET and POST for all of your incoming HTTP requests. Representational state transfer application programming interface methodology (RESTful API) hasPUT and DELETE so use them for updates and deletions (wiki).

For example in this Express.js route, instead of using POST to update a record, you can use PUT:

app.post('/comments/update/:id', routes.comments.update)
app.put('/comments/:id', routes.comments.update)

For more information, take a look at REST API Tutorial.

Stop Using Semicolons with Node.js 不要在Node.js中使用分号

Semicolons are actually optional, because ECMAScript (the standard for Node.js and browser JavaScript implementations) has an automatic semicolon-insertion feature (ASI). Here’s the draft of the ECMAScript 6 (ES6) documentation about ASI.

The gist is that semicolons are optional and except for two cases: in front of the IIFE and inside of the for loop.

The problem with using semicolons:

  • Extra characters to type: In a 1,000-line file there will be at least 1,000 extra symbols
  • Inconsistency: When semicolons are missed due to neglect, the code base still works but becomes inconsistent (solvable by linting, but that’s an extra build step)

Some popular Node.js projects have been written with a semicolon-less style:

  • NPM: the Node.js package manager
  • Request: a module for making HTTP requests

Are you still doubtful because Doug Crockford told you that you had to use semicolons? Then maybe you should read An Open Letter to JavaScript Leaders Regarding Semicolons.

Stop Using Comma-First Style 不要使用逗号优先风格

Okay, this topic is very subjective and probably not that important, but I want to voice my dislike for the comma-first style. Please, stop the madness!

The style in question is often seen when one might write arrays and objects with a comma at the beginning of lines instead of at the end. For example, we can define an array:


var arr = [ 'nodejs'
  , 'python'
  , 'ruby'
  , 'php'
  , 'java'
]

Or in a more traditional style it would look like this:


var arr = [ 'nodejs', 
  'python', 
  'ruby', 
  'php',
  'java'
]

Please, don’t do the former. I don’t care how much better it might be for catching missing commas. The comma-first style just look ridiculous, because we would never use this style in our normal language writing. Nobody writes like this:


Paleo lifestyle is good for ,adult men ,adult women ,children ,and elderly people.

In my humble opinion, comma-first style is hard for the brain to adapt and just plain silly.

Stop Limiting Your Connections with Default MaxSockets Value 不要使用缺省MaxSockets值限制连接

The default maxSockets value is 5 and it determines the limit on number of sockets per host (official docs).

To avoid bottlenecking your system just use something like this:


var http = require('http')
http.globalAgent.maxSockets = 10

Or, if you want to make it unlimited:


equire('http').globalAgent.maxSockets = Infinity

Here is a good comparison article Node.js Connection Pooling.

Another approach is to disable pooling all together (agent: false) like LinkedIn didor Substack recommends in his hyperquest module.

Conclusion About Things to Stop Doing with Node.js 关于不应该用Node.js做的事情的结论

Of course, this list of seven things you should immediately stop doing with Node.js is subjective, but it was born out of careful and ongoing observation, as well as some painful real-world experience (i.e., * in package.json). What is on your list of things not to do with Node.js?

当然,这7条不应该用Node.js做的事情的列表是主观的,但这些也是通过谨慎和持续的观察,以及一些痛苦的经验得来的(亦即在package.json里)。你自己的不应该用Node.js列表是什么?

原文链接:http://webapplog.com/seven-things-you-should-stop-doing-with-node-js/

本文链接:http://bookshadow.com/weblog/2014/06/15/seven-things-you-should-stop-doing-with-nodejs/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

评论
  1. Faris Faris 发布于 2014年6月25日 18:17 #

    我只想说,配图真个性

张贴您的评论