Node.js、express 以及在 app.configure 中使用开发与生产 [英] Node.js, express, and using development versus production in app.configure
问题描述
让 express 知道我在什么环境中最简单的方法是什么?例如.我想根据我所在的环境执行以下操作以连接到 redis.这可以从命令行完成吗?
What is the easiest method to let express know what environment I am in? E.g. I want do do the below to make a connection to redis depending on what env I am in. Can this be done from the command line?
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
var r = require("redis").createClient(6379,'127.0.0.1');
});
app.configure('production', function(){
app.use(express.errorHandler());
r = redis.createClient(6379,'46.137.195.230', { detect_buffers: true });
});
推荐答案
你的方法没问题,但你可以做一些更通用的事情,比如将 Redis 的配置数据存储在一个文件中,或者像参数一样传递主机和端口:
Your approach is ok, but you can make something more generic, like storing the config data for Redis in a file or passing the host and port like arguments:
node app.js REDIS_HOST REDIS_PORT
然后在您的应用程序中,您可以使用 process.argv 获取它们:
Then in your app you can grab them using process.argv:
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
var r = require("redis").createClient(process.argv[2], process.argv[3]);
});
app.configure('production', function(){
app.use(express.errorHandler());
var r = require("redis").createClient(process.argv[2], process.argv[3], { detect_buffers: true });
});
更新:
Express 将通过查看 NODE_ENV 变量 (process.env.NODE_ENV) 来了解您所处的环境:https://github.com/visionmedia/express/blob/master/lib/application.js#L55
Express will know in what environment you're in by looking at the NODE_ENV variable (process.env.NODE_ENV): https://github.com/visionmedia/express/blob/master/lib/application.js#L55
您可以在启动应用程序时设置该变量,如下所示:NODE_ENV=production node app.js
(推荐),在您的节点应用程序中手动设置 process.env.NODE_ENV 在 Express 代码之前或将里卡多说的 ~/.profile 中的环境变量.
You can set that variable when starting the app like so: NODE_ENV=production node app.js
(recommended), setting process.env.NODE_ENV manually in your node app before the Express code or putting that env var in ~/.profile like Ricardo said.
这篇关于Node.js、express 以及在 app.configure 中使用开发与生产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!