Loading

nodejs 伪全局变量模块

使用这个文件可以实现不同文件中读写变量,适合当做共享变量
文件名:globals.ts

let globals:any = {
    myGlobal: {
        value: 'can be anytype: String, Array, Object, ...'
    },
    aReadonlyGlobal: {
        value: 'this value is readonly',
        protected: true
    },
    dbConnection: {
        value: 'mongoClient.db("database")'
    },
    myHelperFunction: {
        value: function () { console.log('do help') }
    },
};

module.exports.get = function (key:any) {
    // return variable or false if not exists
    return globals[key] && globals[key].value ? globals[key].value : false;
};

module.exports.set = function (key:any, value:any) {
    // exists and is protected: return false
    if (globals[key] && globals[key].protected && globals[key].protected === true)
        return false;
    // set global and return true
    globals[key] = { value: value };
    return true;
};
posted @ 2023-06-19 13:59  这个世界太乱  阅读(21)  评论(0)    收藏  举报