app.set()
and app.get()
allow for the storage of custom properties within the app
object without interfering with built-in properties. This means you can use them to store any app-level data without worry.
You have the option to store the chosen port
using either:
app.set(port, process.env.PORT || 3000)
and then retrieve it using
app.get('port')
Alternatively, you can go with:
const port = process.env.PORT || 3000;
Both methods are effective; the choice between them is a personal one. Personally, I prefer using const port = xxxx
as the port value typically doesn't need to be accessed by other code once the server is running.
Is there a reason for utilizing app.set() and app.get()?
The advantage of app.get()
is that any code with access to the app
object can easily retrieve the stored property. This makes it convenient for storing app-level data that multiple parts of your codebase may need, even if they are spread across different modules. However, in the case of the port number, it's usually only needed locally, so storing it in a variable works just fine.