code

경로에서 액세스 할 수있는 app.js의 전역 변수?

codestyles 2020. 10. 11. 10:34
반응형

경로에서 액세스 할 수있는 app.js의 전역 변수?


변수를에서 설정하고 app.js모든 경로에서 최소한 경로에있는 index.js파일 에서 사용할 수있게하려면 어떻게해야합니까 ? 익스프레스 프레임 워크 사용 및node.js


전역 변수를 만들려면 var키워드 없이 선언하면됩니다 . (일반적으로 이것은 모범 사례는 아니지만 경우에 따라 유용 할 수 있습니다. 변수를 모든 곳에서 사용할 수있게되므로주의하십시오.)

다음은 visionmedia / screenshot-app 의 예입니다.

app.js 파일 :

/**
 * Module dependencies.
 */

var express = require('express')
  , stylus = require('stylus')
  , redis = require('redis')
  , http = require('http');

app = express();

//... require() route files

파일 경로 /main.js

//we can now access 'app' without redeclaring it or passing it in...

/*
 * GET home page.
 */

app.get('/', function(req, res, next){
  res.render('index');
});

//...

실제로 Express 개체에서 사용할 수있는 "set"및 "get"메서드를 사용하여이 작업을 수행하는 것은 매우 쉽습니다.

다음과 같이 예를 들어, 다른 위치에서 사용하려는 구성 관련 항목이 포함 된 config라는 변수가 있다고 가정합니다.

app.js에서 :

var config = require('./config');

app.configure(function() {
  ...
  app.set('config', config); 
  ...
}

route / index.js에서

exports.index = function(req, res){
  var config = req.app.get('config');
  // config is now available
  ...
}

이를위한 깔끔한 방법은 app.localsExpress 자체에서 제공하는 사용 입니다. 다음 은 문서입니다.

// In app.js:
app.locals.variable_you_need = 42;

// In index.js
exports.route = function(req, res){
    var variable_i_needed = req.app.locals.variable_you_need;
}

전역 변수를 선언하려면 전역 개체를 사용해야 합니다. global.yourVariableName과 같습니다. 그러나 그것은 진정한 방법이 아닙니다. 모듈간에 변수를 공유하려면 다음과 같은 주입 스타일을 사용하십시오.

someModule.js :

module.exports = function(injectedVariable) {
    return {
        somePublicMethod: function() {
        },
        anotherPublicMethod: function() {
        },
    };
};

app.js

var someModule = require('./someModule')(someSharedVariable);

또는 대리 개체를 사용하여 수행 할 수 있습니다. 허브 처럼 .

someModule.js :

var hub = require('hub');

module.somePublicMethod = function() {
    // We can use hub.db here
};

module.anotherPublicMethod = function() {
};

app.js

var hub = require('hub');
hub.db = dbConnection;
var someModule = require('./someModule');

간단히 설명하면 다음과 같습니다.

http://www.hacksparrow.com/global-variables-in-node-js.html

따라서 Express.js와 같은 프레임 워크와 같은 일련의 Node 모듈로 작업하고 있는데 갑자기 일부 변수를 전역으로 만들어야 할 필요성을 느낍니다. Node.js에서 변수를 전역으로 만드는 방법은 무엇입니까?

이것에 대한 가장 일반적인 조언은 "var 키워드없이 변수를 선언"하거나 "전역 개체에 변수를 추가"또는 "GLOBAL 개체에 변수를 추가"하는 것입니다. 어느 것을 사용합니까?

먼저 전역 객체를 분석해 보겠습니다. 터미널을 열고 노드 REPL (프롬 트)을 시작하십시오.

> global.name
undefined
> global.name = 'El Capitan'
> global.name
'El Capitan'
> GLOBAL.name
'El Capitan'
> delete global.name
true
> GLOBAL.name
undefined
> name = 'El Capitan'
'El Capitan'
> global.name
'El Capitan'
> GLOBAL.name
'El Capitan'
> var name = 'Sparrow'
undefined
> global.name
'Sparrow'

이것은 도움이되는 질문 이었지만 실제 코드 예제를 제공하면 더 많을 수 있습니다. 링크 된 기사조차 실제로 구현을 보여주지는 않습니다. 그러므로 나는 겸손하게 다음을 제출합니다.

당신의에서 app.js파일, 파일의 맨 위에 :

var express = require('express')
, http = require('http')
, path = require('path');

app = express(); //IMPORTANT!  define the global app variable prior to requiring routes!

var routes = require('./routes');

app.js에는 메소드에 대한 참조 가 없습니다 app.get(). 개별 경로 파일에 정의 된 상태로 둡니다.

routes/index.js:

require('./main');
require('./users');

마지막으로 실제 경로 파일 routes/main.js:

function index (request, response) {
    response.render('index', { title: 'Express' });
}

app.get('/',index); // <-- define the routes here now, thanks to the global app variable

내가 선호하는 방법은 순환 종속성 *을 사용하는 것입니다.

  • app.js var app = module.exports = express();에서 비즈니스의 첫 번째 주문으로 정의
  • 이제 사실 이후에 필요한 모든 모듈 var app = require('./app')이 액세스 수 있습니다.


app.js

var express   = require('express');
var app = module.exports = express(); //now app.js can be required to bring app into any file

//some app/middleware, config, setup, etc, including app.use(app.router)

require('./routes'); //module.exports must be defined before this line


route / index.js

var app = require('./app');

app.get('/', function(req, res, next) {
  res.render('index');
});

//require in some other route files...each of which requires app independently
require('./user');
require('./blog');

다른 사람들이 이미 공유했듯이 app.set('config', config)이것에 좋습니다. 기존 답변에서 볼 수 없었던 매우 중요한 것을 추가하고 싶었습니다. Node.js 인스턴스는 모든 요청에서 공유되므로 일부 config또는 router객체를 전역 적으로 공유하는 것이 매우 실용적 일 수 있지만 런타임 데이터를 전역 적으로 저장하는 것은 요청과 사용자간에 사용할 수 있습니다 . 이 매우 간단한 예를 고려하십시오.

var express = require('express');
var app = express();

app.get('/foo', function(req, res) {
    app.set('message', "Welcome to foo!");
    res.send(app.get('message'));
});

app.get('/bar', function(req, res) {
    app.set('message', "Welcome to bar!");

    // some long running async function
    var foo = function() {
        res.send(app.get('message'));
    };
    setTimeout(foo, 1000);
});

app.listen(3000);

을 (를) 방문 /bar하고 다른 요청이 /foo이면 메시지는 "Welcome to foo!"가됩니다. 이것은 어리석은 예이지만 요점을 이해합니다.

다른 node.js 세션이 변수를 공유하는 이유 에 대해 흥미로운 점이 있습니다 . .


가장 쉬운 방법은 초기에 app.js에서 전역 변수를 선언하는 것입니다.

global.mySpecialVariable = "something"

then in any routes you can get it:

console.log(mySpecialVariable)

I solved the same problem, but I had to write more code. I created a server.js file, that uses express to register routes. It exposes a function,register , that can be used by other modules to register their own routes. It also exposes a function, startServer , to start listening to a port

server.js

const express = require('express');
const app = express();

const register = (path,method,callback) => methodCalled(path, method, callback)

const methodCalled = (path, method, cb) => {
  switch (method) {
    case 'get':
      app.get(path, (req, res) => cb(req, res))
      break;
    ...
    ...  
    default:
      console.log("there has been an error");
  }
}

const startServer = (port) => app.listen(port, () => {console.log(`successfully started at ${port}`)})

module.exports = {
  register,
  startServer
}

In another module, use this file to create a route.

help.js

const app = require('../server');

const registerHelp = () => {
  app.register('/help','get',(req, res) => {
    res.send("This is the help section")
  }),
  app.register('/help','post',(req, res) => {
    res.send("This is the help section")
  })}

module.exports = {
  registerHelp
}

In the main file, bootstrap both.

app.js

require('./server').startServer(7000)
require('./web/help').registerHelp()

John Gordon's answer was the first of dozens of half-explained / documented answers I tried, from many, many sites, that actually worked. Thank You Mr Gordon. Sorry I don't have the points to up-tick your answer.

I would like to add, for other newbies to node-route-file-splitting, that the use of the anonymous function for 'index' is what one will more often see, so using John's example for the main.js, the functionally-equivalent code one would normally find is:

app.get('/',(req, res) {
    res.render('index', { title: 'Express' });
});

I used app.all

The app.all() method is useful for mapping “global” logic for specific path prefixes or arbitrary matches.

In my case, I'm using confit for configuration management,

app.all('*', function (req, res, next) {
    confit(basedir).create(function (err, config) {
        if (err) {
            throw new Error('Failed to load configuration ', err);
        }
        app.set('config', config);
        next();
    });
});

In routes, you simply do req.app.get('config').get('cookie');

참고URL : https://stackoverflow.com/questions/9765215/global-variable-in-app-js-accessible-in-routes

반응형