项目开发讲究通配,一个配置到处使用,而且还各有各的环境来确定各自的配置文件信息,看如下代码:
require('../lib/util');// 此配置文件适合多人合作设置各自不同环境的配置信息var env = 'dev'; // dev or productvar devloper = 'antianlu'; // 开发者:defaults,your name,默认是系统默认的配置,开发者名字按照各自环境配置自己的配置文件信息,适合多人合作情况var http = 'http://'; //http:// or https://var settings = { base: { appName: "Ablog", version: "0.0.1", env: env, cookie: { secret: "0o80ilpoablog", id: 'ablog' }, session: { secret: "0o80ilpoablog", id: 'ablog' }, desc:'基本配置' }, dev: { defaults: { hostname: { host: "127.0.0.1", port: 3000 }, mongodb: { host: "localhost", port: "27017", dbname: "blog", username: "", password: "" }, mysql: { host: '127.0.0.1://mysql', username: 'mysql', password: 'test' } }, antianlu: { hostname: { host: "127.0.0.1", port: 3000 }, mongodb: { host: "localhost", port: "27017", dbname: "blog", username: "", password: "" }, mysql: { host: '127.0.0.1://mysql', username: 'mysql', password: 'test' } }, desc:'开发环境配置' }, product: { hostname: { host: "https://www.ablog.com", port: 80 }, mongodb: { host: "", port: "", name: "ablog", username: "uname", password: "pwd" }, mysql: { host: '192.168.1.88://mysql', username: 'ablog', password: 'test' }, desc: '网站发布地址配置' }}var c = env === 'dev' ? settings[env][devloper] : settings[env], mongo = c.mongodb, hostname = c.hostname;c.mongodb.url = "mongodb://" + mongo.host + ":" + mongo.port + "/" + mongo.dbname;c.hostname.url = http + hostname.host + ":" + hostname.port;module.exports = settings.base.extend(c);
../lib/util文件内容,相当于jquery的extend,深度拷贝
/** * Created by Administrator on 14-5-15. */Object.prototype.extend = function () { var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy; if (typeof target === "boolean") { deep = target; target = arguments[1] || {}; i = 2; } if (typeof target !== "object" && typeof target !== "function") { target = {}; } if (length === i) { target = this; --i; } for (; i < length; i++) { if ((options = arguments[i]) != null) { for (name in options) { src = target[name]; copy = options[name]; if (target === copy) { continue; } if (deep && copy && (typeof copy === 'object' || typeof copy === 'array') && !copy.nodeType) { var clone = src && (typeof src === 'object' || typeof src === 'array') ? src : typeof copy === 'array' ? [] : {}; target[name] = this.extend(deep, clone, copy); } else if (copy !== undefined) { target[name] = copy; } } } } return target;}module.exports ={ merge: function (o1, o2, override) { for (var p in o2) { if (o2.hasOwnProperty(p) && (!o1.hasOwnProperty(p) || override)) { o1[p] = o2[p]; } } }}