Say I have one .js
file containing a javascript object. I want to be able to access that object and all of its functionality from another .js
file in t
This is the way I create modules:
myModule.js
var MyObject = function() {
// This is private because it is not being return
var _privateFunction = function(param1, param2) {
...
return;
}
var function1 = function(param1, callback) {
...
callback(err, results);
}
var function2 = function(param1, param2, callback) {
...
callback(err, results);
}
return {
function1: function1
,function2: function2
}
}();
module.exports = MyObject;
And to use this module in another JS file, you can simply use require
and use your object as normal:
someFile.js
var myObject = require('myModule');
myObject.function1(param1, function(err, result) {
...
});
In one file:
module.exports.myObj = some object...;
In the other:
Obj = require('myFile.js').myObj;
Everything in a js file on node is local to that file unless you put it in the export object. This actually is very different from JavaScript in a browser--in the browser all files that get imported act together like one big file.
You can kinda think about node files as though you are creating a module object and passing it' into a function surrounding your code.
module = { 'exports' : {} };
(function(module){
//your js file
...
})(module)
the simplest approach, in my opinion:
write Person.js: (note it comes with ctor)
module.exports = function (firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.fullName = function () {
return this.firstName + ' ' + this.lastName;
}
}
and consume it:
var person = require('./Person.js');
var person1 = new person('James', 'Bond');
console.log(person1.fullName());
note that in this simple solution all methods are "public".
ref: https://www.tutorialsteacher.com/nodejs/nodejs-module-exports
Of course you can. In my example I use obj to hold my config info. I put it in a file called index.js
in config
folder. This makes the index the preferred choice to be picked when I import 'config'
. I have 2 exports here one for my node and api stuff and the other for my db. You can ignore the first bit where I set the environment.
const environment = {
development: {
isProduction: false
},
production: {
isProduction: true
}
}[ process.env.NODE_ENV || 'development' ];
export default Object.assign({
host: 'localhost',
port: '3000',
remoteApi: {
token: {
'X-Token': '222222222222222222'
},
base: 'https://www.somedomain.com/api'
}
}, environment);
export const db = {
dbHost: 'localhost',
dbPort: 176178
};
Calling import config from '../config';
will pick the default one. And if I specify I can get the db
export import { db } from '../config';