Node.js 根据需要调用函数

Dev*_*nux 4 javascript node.js node-modules

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

应用程序.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
Run Code Online (Sandbox Code Playgroud)

数据库.js

export class Database {
    // some functions here
}
Run Code Online (Sandbox Code Playgroud)

模型.js

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

    insert() {}
    find() {}
    delete() {}
    update() {}
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*nde 5

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

abc/index.js

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

calledOnce();

console.log('Also once');

module.exports = {
    ...
}
Run Code Online (Sandbox Code Playgroud)