珠峰培训

Node Style Guide [Node.js 编码规范]

作者:

2015-08-01 17:46:15

102

 Node Style Guide [Node.js 编码规范]
 
 发布于 2年前  作者 dead-horse  2839 次浏览

可能大部分的同学在写 node 的时候,都会有自己的风格,但是 node 的代码,稍不注意就变成了一坨shit。最近这几天在整理公司的 node 编程相关的资料,于是把 felixge 的node-style-guide翻译了一下,顺便加上了一些这两年 node 实际项目中以及 node 源码中的一些代码风格规范。

其中有一些老生长谈的东西,例如用空格还是用tab, { 放哪里,单引号还是双引号。还有一些在日常编码里面非常容易忽视的东西,例如:

使用有意义的判断条件

所有复杂的条件判断都需要赋予一个有意义的名字或者方法。

Right:

var isValidPassword = password.length >= 4 && /^(?=.*\d).{4,}$/.test(password);if (isValidPassword) {
  console.log('winning');}

Wrong:

if (password.length >= 4 && /^(?=.*\d).{4,}$/.test(password)) {
  console.log('losing');}
尽早的从函数中返回

为了避免深入嵌套的 if 语句,请尽早的从函数中返回。

Right:

function isPercentage(val) {
  if (val < 0) {
    return false;
  }

  if (val > 100) {
    return false;
  }

  return true;}

Wrong:

function isPercentage(val) {
  if (val >= 0) {
    if (val < 100) {
      return true;
    } else {
      return false;
    }
  } else {
    return false;
  }}
给你的闭包命名

请尽量给你的闭包、匿名函数命名。这让人知道你在意这个函数,更重要的是,这将会产生可读性更好的堆栈跟踪和CPU调用信息等。

Right:

req.on('end', function onEnd() {
  console.log('winning');});

Wrong:

req.on('end', function() {
  console.log('losing');});
不要嵌套闭包

使用闭包,但是不要嵌套他们,否则你的代码将会一团糟。

Right:

setTimeout(function() {
  client.connect(afterConnect);}, 1000);function afterConnect() {
  console.log('winning');}

Wrong:

setTimeout(function() {
  client.connect(function() {
    console.log('losing');
  });}, 1000);

点击查看完整版本,欢迎star, fork, pull request.

赶快来适应 node 的风格,写出漂亮的 node 代码吧 !:D