GUIDE

The road ahead will be long and our climb will be steep

Nodejs Best Practices

| Comments

Embrace async

Before
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let af = () => promise;
let bf = () => promise;

let cf = () => {
  return af().then(() => {
    return bf().then(result => {
      let t = result;
      return ...;
    })
  });
}

let df = () => {
  cf().then().catch();
}
After
1...
2let cf = async () => {
3  let r1 = await af();
4  let r2 = await bf();
5  return ...;
6}
7...

Now we need babel to compile this syntax

NPM

  • start project use npm init

  • use .npmrc

npm config set save=true
npm config set save-exact=true
  • add scripts to package.json
"scripts": {
  "debug": "npm run es6 -- --nolazy --debug-brk=5858 src/server.js",
  "es6": "node_modules/.bin/babel-node",
  "es6:watch": "node_modules/.bin/babel-watch",
  "eslint": "node_modules/.bin/eslint",
  "start": "npm run es6:watch -- src/server.js",
  "start:prod": "npm run es6 -- src/server.js",
  "test": "npm run eslint -- \"src/**/*.js\" && make tests"
}

Style guide

ESlint, JSLint and so on.

Handle errors and logging important messages

Some syntax like:

// if use express
let errorCatch = (err, req, res, next) => {
  logger.error(err.message, "\n" + err.stack);
  // some logic ...
  res.status(err.code || 500);
  res.json({ error: err.message });
}

Process management

  • automatically restart app

  • cluster app

Use Content-Security-Policy in web application

reduce XSS (Cross-Site scripting) risks on modern browsers, https://content-security-policy.com/.

Comments