node.js - Module.export 一个 'default' 函数

标签 node.js

我想编写一个导出默认函数和属性列表的模块(它们也是函数)。 基本上这个模块将允许这种使用消费者端:

let db_connection = fake_database_connection_instance()
let db = require('./db.js')(db_connection)
db.find({id:1})

因此默认函数应该只将数据库连接实例传递给模块。 这是无效代码

module.exports = {
    //init should go away and replaced by a 'default' function when this module is called
    init: function (connection) {
        this.connection= connection;
        return this;
    },
    find: function (query) {
        return new Promise(function (resolve, reject) {
            this.connection.find(query, function (err, docs) {
                if (err) {
                    return reject(err);
                }
                return resolve(docs);
            });
        });
    }
}

我想避免 new 关键字(消费者端),所以我必须删除那些 this,我知道。这里的问题是 2:

  • 如何导出在 require('./db.js')() 上调用的默认函数和其他函数,例如require('./db.js').find()?
  • 如何将连接实例从默认函数传递给 find()

EDIT 按照我写的@Igor Raush ES6 Class 解决方案,但仍然 db is not defined

class DB {
    constructor(db) {
        this.db = db;
    }
    find(query) {
        return new Promise( (resolve, reject) => {
            this.db.find(query, function (err, docs) {
                if (err) {
                    return reject(err);
                }
                return resolve(docs);
            });
        });
    }
}

最佳答案

您可以将默认函数添加到module.exports 并使用外部变量_conn 来存储连接:

let _conn;

module.exports = (connection) => {
  _conn = connection;
};

之后,您可以将 find 函数添加到 module.exports 对象:

module.exports.find = (query) => {
  return new Promise(function(resolve, reject) {
    _conn.find(query, function(err, docs) {
      if (err) {
        return reject(err);
      }
      resolve(docs);
    });
  });
}

关于node.js - Module.export 一个 'default' 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45578234/

相关文章:

node.js - AWS Cognito 模拟

javascript - 扎 PIL 还是自己动手?

javascript - Multer 无法将文件上传到我的服务器,已经尝试了两天了,眼袋游戏在这一款中很强

javascript - NodeJS/JS 如何通过 sha256 正确散列对象 json 和字符串(串联)

javascript - 使用状态和模板文字进行重定向 react

javascript - 从嵌套 JSON 中获取值

node.js - 使用nodejs从异步函数返回列表

javascript - User.id 未定义

PHP 执行 casperjs/phantomjs 脚本

javascript - node.js:如何在 koa 中使用 Passport