Node.js에서 파일간에 변수를 공유 하시겠습니까?
다음은 2 개의 파일입니다.
// main.js
require('./modules');
console.log(name); // prints "foobar"
// module.js
name = "foobar";
"var"이 없으면 작동합니다. 그러나 내가 가질 때 :
// module.js
var name = "foobar";
이름은 main.js에서 정의되지 않습니다.
전역 변수가 나쁘다는 말을 들었으며 참조 전에 "var"을 사용하는 것이 좋습니다. 그러나 이것이 전역 변수가 좋은 경우입니까?
전역 변수는 거의 좋은 일이 아닙니다 (예외로는 예외가 될 수도 있습니다 ...). 이 경우 실제로 "name"변수를 내보내려는 것처럼 보입니다. 예 :
// module.js
var name = "foobar";
// export it
exports.name = name;
그런 다음 main.js에서 ...
//main.js
// get a reference to your required module
var myModule = require('./module');
// name is a member of myModule due to the export above
var name = myModule.name;
글로벌 var
이 최선의 선택 인 시나리오를 찾을 수는 없지만 물론 사용할 수는 있지만이 예제를 살펴보면 동일한 방법을 수행하는 더 좋은 방법을 찾을 수 있습니다.
시나리오 1 : 구성 파일에 내용 저장
애플리케이션 전체에서 동일한 값이 필요하지만 환경 (프로덕션, 개발자 또는 테스트), 예를 들어 메일러 유형에 따라 변경됩니다.
// File: config/environments/production.json
{
"mailerType": "SMTP",
"mailerConfig": {
"service": "Gmail",
....
}
과
// File: config/environments/test.json
{
"mailerType": "Stub",
"mailerConfig": {
"error": false
}
}
(개발자에게도 비슷한 설정을하십시오)
어떤 구성을로드할지 결정하려면 기본 구성 파일을 만듭니다 (이 파일은 응용 프로그램 전체에서 사용됨)
// File: config/config.js
var _ = require('underscore');
module.exports = _.extend(
require(__dirname + '/../config/environments/' + process.env.NODE_ENV + '.json') || {});
그리고 지금 당신은 데이터를 얻을 수있는 이 같은를 :
// File: server.js
...
var config = require('./config/config');
...
mailer.setTransport(nodemailer.createTransport(config.mailerType, config.mailerConfig));
시나리오 2 : 상수 파일 사용
// File: constants.js
module.exports = {
appName: 'My neat app',
currentAPIVersion: 3
};
그리고 이런 식으로 사용하십시오
// File: config/routes.js
var constants = require('../constants');
module.exports = function(app, passport, auth) {
var apiroot = '/api/v' + constants.currentAPIVersion;
...
app.post(apiroot + '/users', users.create);
...
시나리오 3 : 헬퍼 기능을 사용하여 데이터 가져 오기 / 설정
이것의 열렬한 팬은 아니지만 최소한 '이름'(OP의 예를 인용)의 사용을 추적하고 유효성 검사를 할 수 있습니다.
// File: helpers/nameHelper.js
var _name = 'I shall not be null'
exports.getName = function() {
return _name;
};
exports.setName = function(name) {
//validate the name...
_name = name;
};
그리고 그것을 사용하십시오
// File: controllers/users.js
var nameHelper = require('../helpers/nameHelper.js');
exports.create = function(req, res, next) {
var user = new User();
user.name = req.body.name || nameHelper.getName();
...
There could be a use case when there is no other solution than having a global var
, but usually you can share the data in your app using one of these scenarios, if you are starting to use node.js (as I was sometime ago) try to organize the way you handle the data over there because it can get messy really quick.
If we need to share multiple variables use the below format
//module.js
let name='foobar';
let city='xyz';
let company='companyName';
module.exports={
name,
city,
company
}
Usage
// main.js
require('./modules');
console.log(name); // print 'foobar'
Update
Save any variable that want to be shared as one object. Then pass it to loaded module so it could access the variable through object reference..
// myModule.js
var shared = null;
function init(obj){
shared = obj;
}
module.exports = {
init:init
}
.
// main.js
var myModule = require('./myModule.js');
var shares = {value:123};
myModule.init(shares);
Old Answer
To share variable between module you can use function to get the value of variable between the main and the modules.
//myModule.js
var mainFunction = null; //You can also put function reference in a Object or Array
function functionProxy(func){
mainFunction = func; //Save the function reference
}
// --- Usage ---
// setTimeout(function(){
// console.log(mainFunction('myString'));
// console.log(mainFunction('myNumber'));
// }, 3000);
module.exports = {
functionProxy:functionProxy
}
.
//main.js
var myModule = require('./myModule.js');
var myString = "heyy";
var myNumber = 12345;
function internalVariable(select){
if(select=='myString') return myString;
else if(select=='myNumber') return myNumber;
else return null;
}
myModule.functionProxy(internalVariable);
// --- If you like to be able to set the variable too ---
// function internalVariable(select, set){
// if(select=='myString'){
// if(set!=undefined) myString = set;
// else return myString;
// }
// else if(select=='myNumber'){
// if(set!=undefined) myNumber = set;
// else return myNumber;
// }
// else return null;
// }
You can always get the value from main.js
even the value was changed..
a variable declared with or without the var keyword got attached to the global object. This is the basis for creating global variables in Node by declaring variables without the var keyword. While variables declared with the var keyword remain local to a module.
see this article for further understanding - https://www.hacksparrow.com/global-variables-in-node-js.html
With a different opinion, I think the global
variables might be the best choice if you are going to publish your code to npm
, cuz you cannot be sure that all packages are using the same release of your code. So if you use a file for exporting a singleton
object, it will cause issues here.
You can choose global
, require.main
or any other objects which are shared across files.
Please tell me if there are some better solutions.
참고URL : https://stackoverflow.com/questions/3922994/share-variables-between-files-in-node-js
'development' 카테고리의 다른 글
코드 랩 IntelliJ? (0) | 2020.07.24 |
---|---|
Windows가 fork ()해야 할 가장 가까운 것은 무엇입니까? (0) | 2020.07.24 |
Entity Framework 연결 문자열을 어떻게 편집해야합니까? (0) | 2020.07.24 |
XMLHttpRequest에서 onload가 readyState == 4와 같습니까? (0) | 2020.07.24 |
“Microsoft.VisualStudio.TestTools.UnitTesting”누락 된 dll를 찾을 수있는 곳 (0) | 2020.07.24 |