简体   繁体   English

如何访问server.js文件之外的应用程序?

[英]how to access app outside the server.js file?

I have two files: 我有两个文件:

server.js server.js

const app = express();
require('./server/config/crawlerBasedModels.config').basedModels()
.then((models) => {
    app.locals.basedModels = models;
    console.log(app.locals.basedModels);
})
.catch(err => console.log(err));

crawlerBasedModels.config: crawlerBasedModels.config:

const fs = require('fs');
const Promise = require('bluebird');
module.exports = {
basedModels: () => {
    return new Promise((res, rej) => {
        let basedModelsPath = require('../config/exportFolderPath');
        const basedModels = JSON.parse(fs.readFileSync(basedModelsPath + '/basedModels.json'));
        if(basedModels) {console.log(basedModels); return res(basedModels);}
        return rej('couldnt load basedModels file!');
    });
}
};

in console i see: undefined 在控制台中,我看到:未定义

My question is how can I set a global var within my app that will be exposed for the entire of the app lifetime? 我的问题是如何在我的应用程序中设置一个在整个应用程序生命周期内都会公开的全局变量?

There are two ways to accomplish this. 有两种方法可以完成此操作。

<app.js>
const app = module.exports = express();
app.locals.test = 'test is valid';

<anotherfile.js>
const app = require('./app');
console.log(app.locals.test);

Now, anytime you require app , it will set the app.locals and it'll be accessible to you in another file. 现在,只要您需要app ,它就会设置app.locals,您可以在另一个文件中访问它。

Another way to do it is to have a separate blank file, called global.js. 另一种方法是拥有一个单独的空白文件,称为global.js。

<global.js>
empty file

<test1.js>
const global = require('./global');
global.test = 'setting var in test1.js';

<test2.js>
const global = require('./global');
console.log('global vars %j', global);

<node.js runtime>
> const a = require('./test1.js')
> const b = require('./test2.js');
global vars {"test":"setting var in test1.js"}

The only caveat here will be test1 has to be required before you can access the global variable. 唯一需要注意的是,在访问全局变量之前,必须先输入test1。 But, your use case demands that as well, setting something in app.locals and then using it somewhere else. 但是,您的用例也要求在app.locals中进行设置,然后在其他地方使用它。

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

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