You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用app.set()与app.get()是否有特定用途?能否直接硬编码替代?

Hey there! Great question—let's unpack this step by step.

What are app.set() and app.get() actually used for?

In Express, app.set() and app.get() are the framework's built-in way to manage application-level configuration. They're not just for storing ports—here are their key use cases:

  • Express-native configuration: Many core Express features rely on these methods. For example, setting your template engine with app.set('view engine', 'ejs') or defining the views directory with app.set('views', './src/views') tells Express exactly where to look for templates and how to render them.
  • Shared global values: If you have configs that need to be accessed across multiple routes, middleware, or modules (like API keys, environment flags, or CORS settings), storing them with app.set() lets you fetch them from the app instance anywhere using app.get()—no need to pass variables around or pollute the global scope.
  • Centralized config management: In larger projects, keeping all your app's configs in one place (via app.set) makes maintenance way easier. You don't have to hunt through multiple files to find where a setting is defined.

Can I replace this with hardcoded variables like your example?

Absolutely! Your alternative approach works perfectly, and it's totally valid—especially for small apps or when you only need the port value in one place. It's even more readable at a glance for simple use cases.

That said, there are a few scenarios where sticking with app.set()/app.get() makes sense:

  • If your app grows later and other parts (like middleware, routes, or health check endpoints) need to access the port value, you can just call app.get('port') instead of passing the port variable through multiple layers of code.
  • Some third-party Express middleware might expect certain configs to be stored via app.set() (though this is rare, it's something to keep in mind for compatibility).
  • For consistency in larger codebases: If you're already using app.set() for other configs, keeping the port there keeps your configuration pattern uniform.

Example Comparison

Original approach using app.set/app.get:

app.set('port', (process.env.PORT || 3000));
const server = app.listen(app.get('port'), () => {
  console.log('Server|Port: ', app.get('port'));
});

Your readable alternative:

const port = process.env.PORT || 3000;
const server = app.listen(port, () => {
  console.log('Server|Port: ', port);
});

Both work—choose the one that fits your app's size and needs!

内容的提问来源于stack exchange,提问作者user9174319

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:38:09