NodeJS export class with static methods
我正在尝试在NodeJs应用程序上使用静态方法开发一个类,作为Config模块的目的。
我想从不同的模块访问它,而不是每次新的对象都实例化。
1)使用类似下面的方法是否正确,避免类原型?
1 2 3 4 5 6 7 8 9 10 11 12 13 | function Config(){ } Config.svrPort=function(){ return 8080; } Config.dbName=function(){ return"myDbName"; } module.exports = Config; |
2)还有其他解决方案吗?
3)将不同的对象放在同一个模块(例如config.js)中是否也是一种有效的方法?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | exports.server=function(){ return{ port:8080 }; }; exports.database=function(){ return{ name:"myDbName", user:"root", password:"myPassword", host:"localhost", port:3306 }; }; |
最后用它作为:
1 2 3 | var config = require('./config'); config.server().port config.database().name |
这是正确的方法,尽管在您的示例中您可以简单地将值存储为基元:
如果这样说,那么请注意:不要在JavaScript文件中放入任何敏感数据(密码等),而是将它们放在配置文件中。这会将配置与代码分开。并帮助您不泄漏任何潜在的关键信息。
DB-secrets.json
1 2 3 4 | { "password":"...", ... } |
然后你可以通过制作一个包装模块来访问秘密:
1 2 3 | // Wrapper module for db-secrets.json var fs = require('fs'); exports = JSON.parse(fs.readFileSync('db-secrets.json'), 'utf8'); |
或者创建一个db connect模块
1 2 3 4 5 6 7 | var fs = require('fs'); var db = require('db'); var db_secrets = JSON.parse(fs.readFileSync('db-secrets.json'), 'utf8'); export = function() { return db.connect(db_secrets.user, db_secrets.password, ...); }; |
如果您使用git进行源代码管理,您可以轻松地将以下内容添加到
的.gitignore
1 | db-secrets.json |
JS支持对象文字,更不用说你可以在默认的
只需将您想要的每个函数/变量导出为对象文字或附加到导出。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | //just declare any private context as it's own variables in your module, these are static var someVal ="this isn't visible outside the module"; //export single object, with methods attached // NOTE: by default exports exists, and is already module.exports // exports === module.exports exports = module.exports = { getSomeVal: function getSomeVal(){ return someVal; }, getSrvPort: function getSrvPort(){ return 8000; } ... } //alternatively, export each method as property // note, you should name your function assignments, // this helps with debugging. exports.getDbName = function getDbName(){ return"mydb"; }; |
代码实际上只运行一次,所有使用它的地方都会看到相同的选项。
顺便说一句,如果您使用Babel和ES6模块,您只需使用每种方法声明导出...
1 2 3 4 5 6 7 | export function getSrvPort() { return 8000; } export function dbName() { return"mydb"; } |
原型语言中没有类(它只是模仿经典OOP的语法糖)。因此没有静态方法。我的猜测是你需要一个单身(与
1 2 3 4 5 6 7 8 9 10 11 12 13 | var Config = { get svrPort() { return 8080; }, get dbName() { return"myDbName"; }, }; // updated: https://nodejs.org/api/modules.html#modules_caching // module.exports = Object.create(Config); module.exports = Config; |