Skip to content

Latest commit

 

History

History
123 lines (90 loc) · 3.16 KB

Node.js.md

File metadata and controls

123 lines (90 loc) · 3.16 KB

Node.js Cheatsheet

This is a collection of best practices, cheats and tips for doing safe sex with node.js, enjoy!

  1. Formatting
  2. Document Blocks
  3. Module Dependencies
  4. Module Format

Thanks to recent developments in tooling, we no longer have to argue about formatting on node.js (or any javascript) project. The only thing you have to do is have the prettier package installed on your editor.

As, at this time (2021) the most popular editor is Visual Studio Code, to enable auto-formatting on save, you have to create the file .vscode/settings.json with the contents:

{
    "editor.formatOnSave": true,
}

Every method, function, property should be documented with JSDoc Tags.

/**
 * Helper for default value of date types.
 *
 * @param  {number} plusTime The time to add in miliseconds.
 * @return {number} The JS timestamp the future.
 */
exports.defaultDate = function(plusTime) {
  return Date.now() + plusTime;
};

For the Node environment the following order of requiring modules is advised:

  1. Require all core modules
  2. Require all packages
  3. Require all local modules

Each separated by a new line and if possible order by lower to higher level in the stack.

// core modules
const util = require('util');

// packages
const __ = require('lodash'); // use double underscore for lodash
const Promise = require('bluebird'); // lodash is lower in the stack than promises
const express = require('express');

// local modules
const userCtrl = require('./controllers/user.ctrl');

Important: All module dependencies must be declared on the top of the file, no exceptions.

General Layout

Each Node.js module should have the following structure:

  1. Lines must not exceed 80 columns. Exceptions are markdown and markup files.
  2. The @fileoverview tag at the top of the module, with a general description about what this module is about.
  3. The module dependencies as described in Module Dependencies.
  4. Use only exports.property as a way of exporting.
  5. Declare all static properties, functions, constants or enums right after the export statement.
  6. Declare all public / exported methods
  7. Declare all private methods

Even private methods are defined on the exported object.

/**
 * @fileOverview The user Model.
 */

const util = require('util');

const __ = require('lodash');
const config = require('config');
const log = require('logg').getLogger('app.model.User');

const ModelMongo = require('./model-mongo');
const helpers = require('../util/helpers');

/**
 * The supported user roles.
 *
 * @enum {number}
 */
exports.Role = {
  API: 1,
  ADMIN: 2,
};

/**
 * Pre-validation middleware. Set any default values.
 *
 * @param  {function<Error>} next callback
 * @private
 */
exports._setDefaultValues = (next) => {
  next();
};