Node.js在require时调用函数

0g0grzrc  于 2023-06-29  发布在  Node.js
关注(0)|答案(2)|浏览(155)

是否可以在需要时调用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

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

piztneat1#

由于require调用是缓存的,因此当您需要该模块时,模块内的所有代码都将被调用一次。

abc/index.js

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

calledOnce();

console.log('Also once');

module.exports = {
    ...
}
2g32fytz

2g32fytz2#

对于我们中真正懒惰的人来说:

call-function-on-require.js

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

index.js

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

输出

'call function on require'

其他解决方案

或者,如果你喜欢call-function-on-require.js

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

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

相关问题