简体   繁体   English

NodeJS导出类与静态方法

[英]NodeJS export class with static methods

I'm trying to develop a class with static methods on a NodeJs application, as a Config module purpose. 我正在尝试在NodeJs应用程序上使用静态方法开发一个类,作为Config模块的目的。
I would like to access to it from different modules without instantiate every time a new object. 我想从不同的模块访问它,而不是每次新的对象都实例化。

1) Is it correct to use an approach like below, avoiding the class prototype? 1)使用类似下面的方法是否正确,避免类原型?

function Config(){

}

Config.svrPort=function(){
    return 8080;
}

Config.dbName=function(){
    return "myDbName";
}

module.exports = Config;

2) Are there any other solutions? 2)还有其他解决方案吗?

3) Is it also a valid approach to put different objects in the same module (eg config.js) like this? 3)将不同的对象放在同一个模块(例如config.js)中是否也是一种有效的方法?

exports.server=function(){
    return{
        port:8080
    };
};

exports.database=function(){
    return{
        name:"myDbName",
        user:"root",
        password:"myPassword",
        host:"localhost",
        port:3306
    };
};

and finally to use it as: 最后用它作为:

var config = require('./config');
config.server().port
config.database().name

That is the correct approach although in your example you could simply store the values as primitives: Config.SVR_PORT = 8080 , note I rewrote those as "constants", since I don't recommend changing statics. 这是正确的方法,尽管在您的示例中您可以简单地将值存储为基元: Config.SVR_PORT = 8080 ,注意我将其重写为“常量”,因为我不建议更改静态。

When this is said, then please note: Do not put any sensitive data (passwords, etc) in your JavaScript files, but instead put these in a config file. 如果这样说,那么请注意: 不要在JavaScript文件中放入任何敏感数据(密码等),而是将它们放在配置文件中。 This will separate config from code. 这会将配置与代码分开。 And help you not to leak any potential critical information. 并帮助您不泄漏任何潜在的关键信息。

db-secrets.json DB-secrets.json

{
  "password": "...",
  ...
}

Then you can access the secrets by making a wrapper module: 然后你可以通过制作一个包装模块来访问秘密:

// Wrapper module for db-secrets.json
var fs = require('fs');
exports = JSON.parse(fs.readFileSync('db-secrets.json'), 'utf8');

Or make a db connect module db-connect.js : 或者创建一个db connect模块db-connect.js

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, ...);
};

If you use git for source control you can easily add the following to your .gitignore which will make sure your sensitive file is not added to git: 如果您使用git进行源代码管理,您可以轻松地将以下内容添加到.gitignore ,以确保您的敏感文件不会添加到git中:

.gitignore 的.gitignore

db-secrets.json

There are no classes in the prototype languages (it's just a syntax sugar that mimics the classical OOP). 原型语言中没有类(它只是模仿经典OOP的语法糖)。 Hence no static methods. 因此没有静态方法。 My guess is that you want a singleton (which is the same as object literal ). 我的猜测是你需要一个单例(与object literal相同)。

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;

JS supports object literals, not to mention that you can export a single object, or multiple export properties on the default exports object... When the require('./your-module'); JS支持对象文字,更不用说你可以在默认exports对象上导出单个对象或多个导出属性...当require('./your-module'); happens the code in the module is not run again, it simply returns the original export, that has it's own original context. 如果模块中的代码没有再次运行,它只返回原始导出,它具有自己的原始上下文。


Just export each of the functions/variables that you want as either an object literal, or attached to the exports. 只需将您想要的每个函数/变量导出为对象文字或附加到导出。

//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";
};

The code only actually runs once and all places using it will see the same option. 代码实际上只运行一次,所有使用它的地方都会看到相同的选项。


As an aside, if you're using Babel with ES6 modules, you can simply declare your export with each method... 顺便说一句,如果您使用Babel和ES6模块,您只需使用每种方法声明导出...

export function getSrvPort() {
  return 8000;
}

export function dbName() {
  return "mydb";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM