简体   繁体   English

Node.js调用功能

[英]Node.js call function on require

Is it possible to call a function in a Node.js module when it's required. 需要时是否可以在Node.js模块中调用函数。

app.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 database.js

export class Database {
    // some functions here
}

model.js model.js

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

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

Since require calls are cached, all the code inside the module is called once, when you require that module. 因为require调用被缓存,所以当您需要该模块时,模块内的所有代码都将被调用一次。

abc/index.js ABC / index.js

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

calledOnce();

console.log('Also once');

module.exports = {
    ...
}

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

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