Node & Express
October 20, 2022•291 words
Node.js Express Best Practice
tags: Node.js Express best practice
Shueh Chou Lu Dec 17, 2020
Do In Code
Compression: proxy > app.use(compression())
Asynchronous (async.) >> Synchronous (sync.)
* The only reason to use sync. function is the time to start up server.唯一有理由使用同步函數的時機是在最初啟動之時
Static files: proxy > serve-static > res.sendFile()
Console is sync! Always use async or use sync only in development.
* Debugging: debug >> console
* Application: Winston / Bunyan >> console
- Handle Error ( Important!, Detail in next section )
 
* Try-catch
* Promise
Handle Error
Try-catch is synchronous.
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?
callbackinvoked some time later aftermethod(do another thing)happend exception! wait to finish other process
finish method (
do second thing)finish try-catch block
final run (
finish project!)
Category
- Operational Errors
 
* The errors you are/can except.
* Log, Show, Retry/Abort.
- Programmer Errors
 
* The best way to recover from programmer errors is to crash immediately
* Try debug your program rather than handle it.