【问题标题】:Node.js call function on requireNode.js 在 require 上调用函数
【发布时间】:2019-03-16 23:02:06
【问题描述】:

是否可以在需要时调用 Node.js 模块中的函数。

app.js

const Database = require('./database').Database;

const UsersModel = require('./model').Model; // pass the name = Users and database
const AdminsModel = require('./model').Model; // pass the name = Admins and database

数据库.js

export class Database {
    // some functions here
}

model.js

export class Model {
    onModelCreated(name, database) {
        this.name = name;
        this.database = database;
    }

    insert() {}
    find() {}
    delete() {}
    update() {}
}

【问题讨论】:

  • 你的意思是一次还是每次在某个地方需要它?你想达到什么目的?这听起来像是一个 XY 问题...

标签: javascript node.js node-modules


【解决方案1】:

由于require 调用被缓存,模块内的所有代码都会在您需要该模块时调用一次。

abc/index.js

const calledOnce = () => console.log('once');

calledOnce();

console.log('Also once');

module.exports = {
    ...
}

【讨论】:

  • 是否可以在需要时从 app.js 向该函数传递参数?
  • 告诉我你想要达到什么,我会给你一个方法,你想传递什么参数?你为什么不直接导出一个函数并用你想要的参数或一个类来调用它。
  • const Model = require('./model'); const UsersModel = new Model('users', database);
  • 当然可以这样,但我想发布我的nodejs模块,不希望用户每次都这样写。
  • 所以你想神奇地传递参数。你应该创建一个新问题,因为你完全修改了原来的问题,并把你拥有的东西,你想要实现的东西,以及所有你不想要的东西。但似乎您不应该公开 Database 模块并只在包中处理它而不是用户做某事。
猜你喜欢
  • 2011-11-14
  • 2019-05-18
  • 2016-11-15
  • 1970-01-01
  • 2013-11-01
  • 2012-08-10
  • 1970-01-01
  • 1970-01-01
  • 2021-08-17
相关资源
最近更新 更多