I am having a hard time understanding how to export a file and then include it elsewhere on node.js.
Suppose I am working on a game and I want to have the variables which define an object, or more than one, for example a var enemy:
var enemy = {
health: 100,
strengh: 87
};
and I save it in a file vars.js.
How can one import these variables from anywhere in my project where I need them?
Thanks in advance.
You would need to export them.
So Enemy.js:
var enemy = {
health: 100,
strengh: 87
};
exports.health = enemy.health;
exports.strength = enemy.strength;
And in otherjsfile.js:
var Enemy = require('Enemy.js');
//and then you can do
console.log(Enemy.health); ///etc
If the 'enemy' information is changing periodically and you want to get the newest value, you would do:
Object.defineProperty(exports, "health", {
get: function() {
return enemy.health;
}
}); //instead of `exports.health = enemy.health;`
Object.defineProperty(exports, "strengh", {
get: function() {
return enemy.strengh;
}
}); //instead of `exports.strength = enemy.strength;`
you can export from vars.js doing
module.exports = {
health: 100,
strengh: 87
};
or
var enemy = {
health: 100,
strengh: 87
};
module.exports = enemy;
And import using require:
var enemy = require('./path/to/vars');
in file.js:
module.exports = {
health: 100,
strengh: 87
}
in other files:
var enemy = require('./file'); // (or whatever the relative path to your file is