Node & Express

Node.js Express Best Practice

tags: Node.js Express best practice

Shueh Chou Lu  Dec 17, 2020



Do In Code

  1. Compression: proxy > app.use(compression())

  2. Asynchronous (async.) >> Synchronous (sync.)

* The only reason to use sync. function is the time to start up server.唯一有理由使用同步函數的時機是在最初啟動之時

  1. Static files: proxy > serve-static > res.sendFile()

  2. Console is sync! Always use async or use sync only in development.

* Debugging: debug >> console

* Application: Winston / Bunyan >> console

  1. Handle Error ( Important!, Detail in next section )

* Try-catch

* Promise

Handle Error

  1. Try-catch is synchronous.

  2. Express catch all sync. error in default (v.5 catch Promise as well)

What will log?

const callback = async () => {
  console.log('do another thing');
  throw new Error('foo');
  console.log('do more thing');
}

const method = async () => {
  console.log('do first thing');
  await callback();
  console.log('do second thing')
}

const main = async () => {
  try {
    await method();
  } catch (err) {
    console.log('fire try-catch!');
  }

  console.log('finish project!');
}

result:

do first  thing
do another thing
do second thing
finish project!
UnhandledPromiseRejectionWarning: Error: foo
... (error stack)

why?

  1. callback invoked some time later after method (do another thing)

  2. happend exception! wait to finish other process

  3. finish method (do second thing)

  4. finish try-catch block

  5. final run (finish project!)

Category

  1. Operational Errors

* The errors you are/can except.

* Log, Show, Retry/Abort.

  1. Programmer Errors

* The best way to recover from programmer errors is to crash immediately

* Try debug your program rather than handle it.

Do In Configuration

  1. env.NODE_ENV='production';

  2. Rebuild after error, use helpers or init system [1][2]

  3. Multi-threads [1][2]

  4. Caching [Varnish][Nginx]

  5. Reverse-Proxy [Nginx][HAProxy]

More from Yousef Naeem
All posts