Node.js 最佳實作¶
Referrer from express.js best practice.
In most cases, these are still useful in different frameworks or applications.
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!, Detailed 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");
callback();
console.log("do second thing");
};
const main = async () => {
try {
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?¶
callback
invoked some time later aftermethod
(do another thing
).- happened exception! wait to finish other synchronous processes (
do second thing
). - finish try-catch block.
- final run (
finish project!
). - Fire the asynchronous exception!
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.
Do In Configuration¶
env.NODE_ENV='production';
- Rebuild after error, use helpers or init system 1 2
- Multi-threads 3 4
- Caching 5 6
- Reverse-Proxy 7 8
-
Varnish https://www.varnish-cache.org/ ↩
-
HAProxy http://www.haproxy.org/ ↩