javascript - Node.js call function on require - Stack Overflow

Is it possible to call a function in a Node.js module when it's required.app.jsconst Database = re

Is it possible to call a function in a Node.js module when it's required.

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

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() {}
}

Is it possible to call a function in a Node.js module when it's required.

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

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() {}
}
Share Improve this question edited Mar 16, 2019 at 15:02 Devanshu Linux asked Mar 16, 2019 at 14:09 Devanshu LinuxDevanshu Linux 632 silver badges8 bronze badges 1
  • 1 Do you mean once or every time it is required somewhere? What are you trying to achieve with that? This sounds like a XY problem... – Jonas Wilms Commented Mar 16, 2019 at 14:21
Add a ment  | 

2 Answers 2

Reset to default 5

Since require calls are cached, all the code inside the module is called once, when you require that module.

abc/index.js

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

calledOnce();

console.log('Also once');

module.exports = {
    ...
}

for the really lazy among us:

call-function-on-require.js

(() => {
  console.log('call function on require');
})();

index.js

require(`./call-function-on-require`);

output:

'call function on require'

another solution

or, if you like in call-function-on-require.js

module.exports = () => {
  console.log('call function on require');
}

// index.js: require(`./call-function-on-require`)();

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745166990a4614692.html

相关推荐

  • javascript - Node.js call function on require - Stack Overflow

    Is it possible to call a function in a Node.js module when it's required.app.jsconst Database = re

    7小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信