Performance: Environment-based configuration
This affects server startup time and runtime efficiency by controlling which configurations load based on environment.
const env = process.env.NODE_ENV || 'development'; const config = require(`./config/${env}`); app.use(someMiddleware(config));
const config = require('./config/all'); // loads all configs regardless of environment
app.use(someMiddleware(config));| Pattern | Config Loaded | Startup Delay | Memory Usage | Verdict |
|---|---|---|---|---|
| Load all configs unconditionally | All environments | High | High | [X] Bad |
| Load config based on NODE_ENV | Only current environment | Low | Low | [OK] Good |
PORT in an Express app?process.env.VARIABLE_NAME to get environment variables.process. const port = process.PORT; uses wrong property. const port = process.env['port']; uses lowercase key which is case-sensitive and usually environment variables are uppercase.const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});PORT is set to 5000, what will be printed when the server starts?process.env.PORT || 3000, so if PORT is set, it uses that; otherwise, 3000.PORT is set to 5000, the server listens on port 5000 and prints that.const secret = process.env.SECRET_KEY; console.log(secret.length);
TypeError: Cannot read property 'length' of undefined. What is the likely cause?length is accessed on undefined, meaning secret is undefined.SECRET_KEY is not set in environment, process.env.SECRET_KEY is undefined, causing the error.process.env.DB_URL || default. const dbUrl = 'mongodb://localhost/devdb'; if (process.env.NODE_ENV === 'production') dbUrl = process.env.DB_URL; tries to reassign a const variable (error). const dbUrl = process.env.DB_URL && 'mongodb://localhost/devdb'; uses && which returns false if DB_URL is missing. const dbUrl = process.env.DB_URL ? 'mongodb://localhost/devdb' : process.env.DB_URL; reverses the condition, causing wrong assignment.Pass the test and this pattern moves unknown