Obtain separate exports from individual modules - javascript

In modules.js I have this code:
module.exports = {
BookingHotel: function() {
this.getId = function(id) {
return "Hello World";
},
this.getAll = function() {
return "Hello World";
}
},
BookingFlight: function() {
this.book = function() {
return "Hello World";
}
},
}
The modules.js file is becoming too large and difficult to maintain.
How do I separate BookingHotel and BookingFlight into separate files and export them like they currently are?

Make separate files for the objects:
BookingHotel.js
BookingFlight.js
Export the objects from their respective files:
BookingHotel.js:
export default var BookingHotel = function() {
this.getId = function(id) {
return "Hello World";
},
this.getAll = function() {
return "Hello World";
}
}
BookingFlight.js:
export default var BookingFlight = function() {
this.book = function() {
return "Hello World";
}
}
Then import them in the modules.js file and add them to the exports object:
modules.js:
import BookingHotel from 'BookingHotel.js';
import BookingFlight from 'BookingFlight.js';
module.exports = {
BookingHotel: BookingHotel,
BookingFlight: BookingFlight
};

Make a separate JavaScript file for each export in modules.js and have each file export one function, then just require each file and re-export the functions like this:
NOTE: The names of the individual files don't matter as long as they're consistent with the filenames used in modules.js.
BookingHotel.js:
module.exports = {
BookingHotel: function() {
// Your code here
}
};
BookingFlight.js:
module.exports = {
BookingFlight: function() {
// Your code here
}
};
modules.js:
// Get the exports from BookingHotel.js
var BookingHotelExports = require("./BookingHotel.js");
// Get the exports from BookingFlight.js
var BookingFlightExports = require("./BookingFlight.js");
// Combine the individual exports from the two required modules into a new exports variable for this module.
module.exports = {
// BookingHotel is a property of the module.exports object from BookingHotel.js.
BookingHotel: BookingHotelExports.BookingHotel,
// Same here, but from BookingFlight.js.
BookingFlight: BookingFlightExports.BookingFlight
};

Related

Nodejs module extends with other module

Hi i have parent module like this.
// usermgmt.js
var usermgmt = function () {};
usermgmt.prototype.test = function () {
return "test";
};
usermgmt.private = function () {
return "private";
};
module.exports = new usermgmt();
and a Child prototype class like this.
// authentication.js
var usermgmt = require('./usermgmt');
var authentication = function () {};
authentication.prototype.callParent = function () {
usermgmt.private();
};
module.exports = new authentication();
How i implement inheritance? I searched by google but no solution works for me.
Here's a typical way to export a base class and then import it and inherit from it using the more modern syntax:
// a.js
class A {
constructor() {
}
testA() {
return "testA";
}
}
module.exports = A;
Then, in a separate file:
// b.js
const A = require('./a.js');
class B extends A {
constructor() {
super();
}
testB() {
return "testB";
}
}
let x = new B();
x.testA(); // "testA" - this is inherited obviously
x.testB(); // "testB"
As #jfriend00 said, I write these functions with class keyword which is a syntactic sugar for your code!
usermgmt.js
// usermgmt.js
class usermgmt {
constructor() {
}
test() {
return "test";
}
private() {
return "private";
}
}
module.exports = usermgmt;
Write authentication like this.
authentication.js
// authentication.js
var Usermgmt = require('./usermgmt.js');
class authentication extends Usermgmt {
constructor() {
super();
}
callParent() {
console.log(this.private());
}
authFunction() {
console.log(':: authFunction ::');
this.callParent();
}
}
module.exports = authentication;
And usage for authentication will be:
var Authentication = require('./authentication.js');
let auth = new Authentication();
auth.callParent();
auth.authFunction();
console.log(auth.test());
1) Use class and extends syntax which is easier.
2) Return Class and not its instance

Is a Node.js module a singleton?

I used to implement singleton this way:
class MySomething {
constructor(props) {}
}
let myInstance = null;
module.exports = (props) => {
//first time call
if(props) {
myInstance = new MySomething (props);
return myInstance;
} else {
return myInstance;
}
this assumes that at app.js (entry file) I will call first:
require('./MySomething')(props)
then everywhere in the project I use:
const instanceOfSomething = require('./MySomething')();
I discovered that every time I got a new instance!
What's wrong in my code?
I tried also this way:
class MySomething {...}
const mySomething = (function() {
let myInstance = null;
return {
init: function() {
myInstance = new MySomething();
},
getInstance: function() {
return myInstance ;
}
}
})();
module.exports = mySomething;
and I got the some problem when importing this module from different files, anyone can explain to me?
every require of file create new instance of mySomething
UPDATE
I tried this example now:
class MySomething {...}
const mySomething = {
myInstance: null,
init: function() {
myInstance = new MySomething();
},
getInstance: function() {
return myInstance ;
}
}
};
module.exports = mySomething;
The same problem happened, maybe it is related to my project structure, I will explain it here:
the code below belongs to module "facts"
facts folder contains a folder named "dao" this folder contains MySomething.js (the singleton)
in the facts/index.js I have:
const Localstorage = require('./dao/MySomething');
exports.init = (path) => {
Localstorage.init(path)
}
exports.Localstorage = Localstorage;
Now in a folder named "core" which contains the "facts" folder I re-exported the Localstorage again in "index.js" like this:
const facstModule = require('./facts');
exports.Localstorage = facstModule.Localstorage;
Then in "schedule" folder which contains "Runtime.js" within I write:
const { Localstorage } = require('../core');
setTimeout(() => {
const localstorageIns = Localstorage.getInstance(); //this is always null!
}, 5000)
In app.js file (entry point) I did:
const facts = require('./src/facts');
facts.init(__dirname);
Normally instance will be created before the timeout execute the callaback,
But I noticed that there two instance of Localstorage which is singleton
the cleanest way to do a singleton is
class MyClass () { ... }
module.exports = new MyClass()
if you need a singleton that gets instantiated once, I would do:
class MyClass () { ... }
let myClass
const MyClassSingleton = (...args) => {
if (myClass) {
return myClass
}
myClass = new MyClass(...args)
return myClass
}
module.exports = MyClassSingleton
Every require of file create new instance of mySomething because every time you return new object with init method and getInstance method.
If you need singleton you need do like this:
class MySomething {
constructor() {
if (!MySomething.instance) {
MySomething.instance = this;
}
}
getInstance: function() {
return MySomething.instance;
}
}
module.exports = MySomething;
class Singleton {
constructor() {
this.my_obj;
}
static makeObject() {
if (!this.my_obj) {
this.my_obj = new Singleton();
}
return this.my_obj;
}
add() {
return 1
}
}
// so to get the object we need to call the makeobject method
const obj = Singleton.makeObject()
console.log(obj.add());

Calling an object in main.js from a module in Electron

I have an Electron app with 2 modules, one of them being the standard Menu. When I click a menu item, I want it to call an instantiated module's function.
The only solution I've found is to have my instantiated object being a property of the main electron.app object, which is globally available.
Here's my example:
main.js
const electron = require('electron');
const app = electron.app;
const WindowManager = require('components/WindowManager');
let windowManager = new WindowManager(); // <- I want my menu item to call a function from this object
const MainMenu = require('components/MainMenu');
let mainMenu = new MainMenu();
function initApp() {
let menuTemplate = mainMenu.getTemplate();
let menuBuilt = electron.Menu.buildFromTemplate(menuTemplate);
electron.Menu.setApplicationMenu(menuBuilt);
}
function mainTestFileOpen() {
console.log('File open test function in main.js');
}
// I'm trying to avoid doing this
app.testFileOpen = function() {
console.log('Function is part of "app" so globally accessible...');
}
// I'm trying to avoid doing this too
app.appWindowManager = new WindowManager();
// Start the app
app.on('ready', initApp);
components/WindowManager.js
class WindowManager {
constructor() {
this.doFileOpen = this.doFileOpen.bind(this);
}
doFileOpen() {
console.log('File open from WinwdowManager module');
}
}
module.exports = WindowManager;
components/MainMenu.js
const electron = require('electron');
class MainMenu {
constructor() {
this.template = [];
this.init = this.init.bind(this);
this.getTemplate = this.getTemplate.bind(this);
// Initialize
this.init();
}
getTemplate() {
return this.template;
}
init() {
this.template = [{
label: 'File',
submenu: [{
label: "Open File",
click() {
/** Calling a function in main.js does NOT work **/
mainTestFileOpen();
/** Calling an object in main.js doe NOT work **/
windowManager.doFileOpen();
/** If the function is part of "app" then it works **/
electron.app.testFileOpen();
/** If the instantiated object is part of "app" then it works **/
electron.app.appWindowManager.doFileOpen();
}
}]
}]
}
}
module.exports = MainMenu;
I think what I am not getting is the scope of click() in an Electron Menu template.
You're trying to call a function from a different module (every file in Node is its own module, which is different from the typical JS environment) without first importing the module.
It's not enough to just write a function in the main.js module:
function mainTestFileOpen() {
console.log('File open test function in main.js');
}
And expect to call it from the MainMenu.js module. You must first export it:
export function mainTestFileOpen() { ... }
Then, in MainMenu.js, you can import it at the top:
import { mainTestFileOpen } from "../main";
Same thing with windowManager. It doesn't look like you're doing anything with WindowManager from main.js, so just move the import and instantiation to MainMenu.js:
import { WindowManager } from "./WindowManager";
let windowManager = new WindowManager();
And then you'll be able to do:
windowManager.doFileOpen();
Side Note:
You do stuff like this in your constructor: this.doFileOpen = this.doFileOpen.bind(this);
There is no need for this as the only way somebody could call doFileOpen is by calling it on the windowManager instance like so: windowManager.doFileOpen(...).
The same applies to:
this.init = this.init.bind(this);
this.getTemplate = this.getTemplate.bind(this);

Why I lost my variable after browserify

I have "react actions" file. And something going wrong.
'use strict';
var AppDispatcher = require('../dispatcher/AppDispatcher');
var constants = require('../constants/constants');
var URIjs = require('URIjs');
function loadPageData(url) {
//ajax call
}
var InputsRowActions = {
//some methods, like this
changePage: function(page) {
//work with url params..
loadPageData(url);
}
console.log(URIjs) //-> undefined
};
module.exports = InputsRowActions;
I can't understand, why URIjs didn't defined ?
My Gulp browserify task:
var b = browserify('./app/assets/react/app.react.js', {
debug: true
});
b = watchify(b);
b.transform('reactify');
b.on('update', bundle);
function bundle(fileName) {
return b
.bundle()
.pipe(source('app.react.js'))
.pipe(buffer())
.pipe(gulp.dest('app/assets/javascripts/'));
}
gulp.task('browserify', bundle);
I have same problem, with requiring 'lodash'.

reuqure.js how to separate main module to submodules

guys. I have some question about how can i use require.js in my project.
I have some module. For example:
obj.js
var MyModule = (function(){
var myObject = function(){
this.options = {
foo: 'foo',
bar: 'bar'
};
};
myObject.prototype.foo = function(){
console.log(this.options.foo);
};
myObject.prototype.bar = function(){
console.log(this.options.bar);
};
return {
getMyObject : function(){
return new myObject();
}
}
})();
I haven't problems with using my object as solid. I appended to obj.js this code:
define(function(){
return MyModule;
})
And use it in my app.js module
requirejs.config({
baseUrl : 'lib',
paths : {
app:'../js/app'
}
});
require(['app/obj'], function(MyModule){
var someObj = MyModule.getMyObject();
someObj.foo();
someObj.bar();
});
It's all ok. But how can i split MyModule to some submodules? For example. In module i have 1 object, its constructor and two its methods. Can i put constructor to file, for example 'mymodule.myobject.js', foo to 'mymodule.myobject.foo.js' and bar to 'mymodule.myobject.bar.js' and use it with require.js? If it's really, how can i do this?
You can use this way. Expect following file structure
- js
-- constructors
--- objectCostructor.js
-- objects
--- objectModule.js
So the objectCostructor.js is:
define(function(){
return myObject = function(){
this.options = {
foo: 'foo',
bar: 'bar'
}
}
})
And objectModule.js
define(['constructors/objectCostructor'], function(Const){
Const.prototype.foo = function(){
console.log(this.options.foo);
};
Const.prototype.bar = function(){
console.log(this.options.bar);
};
return {
getMyObject : function(){
return new Const();
}
}
})

Categories

Resources