Real Nodejs, No need for libraries, no need to code these yourself!

Tram Ho

When faced with a problem, many of you often look for a library to solve that problem or develop your own. Using the library is like a double-edged sword. It helps to solve the problem quickly but makes the project heavier. Self-development takes a lot of work. In this small blog I list some cases where we don’t need a library, don’t need to code ourselves because nodejs already supports it.

1. Gen UUID v4.

UUID – (universally unique identifier) ​​is interpreted as a unique identification id 128bit long. UUIDs are very commonly used when you need a unique id for the system. UUID v4 is the most commonly used, random uuid type.

1.1 Some support libraries:

1.2 Don’t use libraries:

cryto module added in nodejs v14.17.0. It has provided many methods to support encryption: HMAC, cypher, OpenSSL and also randomUUID to generate UUID.

2. Objects deep comparison

Objects deep comparison is a type of sâu comparison of two objects. Compares two objects that are 100% identical, including nested objects. Need to separate from type:

  • Shadow comparison: Shallow comparison: Compare the list of Object.keys properties and compare the values ​​of the properties.
  • Referential comprison: Compares to references of variables. Because objects are reference type variables.

2.1 Using the defense:

2.2 Using JSON.stringify:

  • Convert the object to json and then compare it like comparing two strings.

  • Isues: Is to fail when comparing similar objects as keys out of order:

2.3 Don’t use libraries, use util.isDeepStrictEqual

Util modules is a nodejs library that provides developers with many commonly used methods. isDeepStrictEqual is a method to compare two objects:

3. Extract domain name from URL

Extract domain is what I need to get the information of a domain such as, subdomain, domain, port.

3.1 using extract-domain library

3.2 Using URL modules

4. API check heath.

In a microservice system, sometimes services need ONE api for the system to call to check if a service is alive (To be able to restart).

4.1 Using express

  • Many other framework libraries.

4.2 Don’t use real, use http module

5. Conclusion:

  • Sometimes paying a little attention to research helps our system become lighter.
  • Thank you everyone for reading
  • Many of you have had a similar case, comment for everyone to know. Happy sharing!!
Share the news now

Source : Viblo