Node.js,在app.configure中表达并使用开发与生产 [英] Node.js, express, and using development versus production in app.configure

查看:367
本文介绍了Node.js,在app.configure中表达并使用开发与生产的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是最简单的方法让我们知道我在做什么环境?例如。我想做下面的连接到redis,取决于我所在的env。可以从命令行完成吗?

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

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 =生产节点app.js (推荐),在您的节点应用程序中手动设置process.env.NODE_ENV,然后才能使用Express代码或放置那个env var在〜/ .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,在app.configure中表达并使用开发与生产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆