Does assigning module.exports to a separate object waste memory - node.js

There are two basic ways that I see Node modules being written. The first setting each function or variable you want to export to its own property on module.exports:
module.exports.foo = function () {
...
}
And the second is creating a new object that has the properties you want to export, and assigning module.exports to that at the end of the file:
var FooObject = {
foo: function () {
...
}
};
...
module.exports = FooObject;
A third thing that I sometimes see is setting module.exports to an object which has all the properties you want to export, but for the purposes of this discussion, that's equivalent to the first method I mentioned:
module.exports = {
foo: function () {
...
}
}
Are we wasting memory by doing it the second way (creating an object and assigning module.exports to that)? I always thought that since all assignment is a reference, a new object should be created when you do module.exports = {...} so these two would be equivalent. Is that not the case?

The last two examples are equivalent. The only difference is that the second one is setting the object by name and the third is setting it by the object literal.

Related

What is the difference between require with curly braces and require normal?

What is the difference between this
const authController = require("../controller/authController");
and this
const { authController } = require("../controller/authController");
my code doesnt work when i call a function like authController.createUser in second one and i wondered thats why?
Thanks for helps.
The difference between example one and example two is that you are using the Destructuring Assignment method in example two. That means, you can destruct an Object, or Array to have the keys of the object as variables.
So, for example if we take this simple object and we start destructuring:
const someObject = {
something1: "1",
something2: "2",
something3: "3",
something4: "4",
};
const { something1 } = someObject;
console.log(something1) // Returns 1
You see that we can use something1 as a "new variable" instead of accessing it by using someObject.something1.
In your case you are including a module / class with the name authController, but if your module doesn't have a method or key called authController, using the following method:
const { AuthController } = ...
won't work, because it's unable to access this method or key.
So, the first one: authController.createUser() will work because you are loading up the entire module without destructuring the module. If you do something like this const { createUser } = require("authController"), you can use it like createUser(...)
Difference between
const authController = require("../controller/authController");
and
const { authController } = require("../controller/authController");
is, when your module exported by default from your .js file we use first syntax, while if there are several modules getting exported from a single .js file we use the second syntax. Also you cannot have more than one default export from a file. Hope that helps.

nodejs function syntax in module.export

consider the following:
let y = doSomething(){ //doesn't work
console.log('sdf')
}
let y = function doSomething(){ //works
console.log('sdf')
}
module.exports = {
getAll(){
}
}
I had never seen this sort of function(inside the module.exports) is it a call or definition?
It differs in that it doesn't have a keyword function, yet it's exported. What is it called? Does it have a specific name, most importantly, what are we actually doing in here? Please leave me a link to finding out more on this sort of definition if possible.
let y = function doSomething() {} called Function expressions
a name can be provided with a function expression. Providing a name allows the function to refer to itself, and also makes it easier to identify the function in a debugger's stack traces:
module.exports = {
getAll(){}
}
It exports an anonymous object which has a getAll() method. It's called Method definitions

'this' in regular function vs fat arrow function in ES6, illustrated with an example of Mongoose

In router/user.js for routing:
router.post('/register', auth.optional, (req, res, next) => {
const {
body: { user }
} = req
// validation code skipped for brevity
const finalUser = new User(user)
finalUser.setPassword(user.password)
// to save the user in Mongo DB
return finalUser.save().then(() => res.json({ user: finalUser.toAuthJSON() }))
})
Post request sent with a body of:
{
"user":{
"email":"leon#idiot.com",
"password": "123abc"
}
}
In model/User.js for database schema:
const UserSchema = new Schema({
email: String,
hash: String,
salt: String
})
// Please note: this is a regular/normal function definition
UserSchema.methods.setPassword = function (password) {
// this references the UserSchema created
this.salt = crypto.randomBytes(16).toString('hex')
console.log(`salt: ${this.salt}`)
this.hash = crypto
.pbkdf2Sync(password, this.salt, 10000, 512, 'sha512')
.toString('hex')
console.log(`hash: ${this.hash}`)
}
Everything works fine now. The log output as:
salt: e7e3151de63fc8a90e3621de4db0f72e
hash: 19dd9fdbc78d0baf20513b3086976208ab0f9eee6d68f3c71c72cd123a06459653c24c11148db03772606c40ba4846e2f9c6d4f1014d329f01d22805fc988f6164fc13d4157394b118d921b9cbd742ab510e4d2fd4ed214a0d523262ae2b2f80f6344fbd948e8c858f95ed9706952db90d415312156a994c65c42921afc8c3e5b1b24a923219445eec8ed62de313ab3d78dc93b715689a552b6449870c5bfcc3bec80c4438b1895cab41f92ef681344ac8578de476a82aa798730cf3a6ef86973a4364a8712c6b3d53ce67ffffd7569b9ade5db09ad95490354c6f7194fdd9d8f8a1cb7ccddf59e701198a1beee59a2dd6afb90ae50e26ea480e9a6d607e4b37857a02016ee4d692d468dd9a67499547eb03fc6cfa676686f7990c2251c9516459288c55584138aed56a5df6c4692f7ef6925e8f3d6f6a0c780c4d80580447f2b1258bea799a8c7eb9da878ab70a94c4227ec03d18d56b2722c315d0e2b2681d81d78d4213288f7305cbbfa377c3b2eb75e0f0b093e6067b14adce4a01f0a7bde8515350a1c987739c12574ec4c49008510e2e7e5534f9b76d15b1af68e43ef54e6b8a1bea859aafd23d6b6bc61d5b1965004cd6dd933545cf755f3e6dfc8f230f37a79a8bc006b9b14465b1b08d60cb45ef3b6a1b73f5afac90bdc58d5ec15c7596dc7e8d503f8dfbd6a3289cf997da2031389c7f3d165e34b29178f3daf76d
3
But it does not work with such a definition:
UserSchema.methods.setPassword = password => {
// what this reference is undefined, so are ones below
this.salt = crypto.randomBytes(16).toString('hex')
console.log(`salt: ${this.salt}`)
this.hash = crypto
.pbkdf2Sync(password, this.salt, 10000, 512, 'sha512')
.toString('hex')
console.log(`hash: ${this.hash}`)
}
The error is:
{
"errors": {
"message": "Cannot set property 'salt' of undefined",
"error": {}
}
}
which means what this referenced is undefined.
What I find online is that fat arrow functions explicitly prevent binding of this, and it's a problem of scopes, that this in fat arrow functions has a scope of its immediate object. But I cannot say that I understand it very well.
1. In this case, what is the scope of this in fat arrow functions?
2. What is the scope, of this, in normal function definitions?
3. How to access the object, in this case: UserSchema, properties (forgive me for less proper words) in fat arrow functions as one does in normal function definitions?
These posts are quite helpful:
Are 'Arrow Functions' and 'Functions' equivalent / exchangeable?
How does the “this” keyword work?
But I am still expecting answers to my specific questions in particular cases, before figuring them out.
The core of your misunderstanding is this:
that this in fat arrow functions has a scope of immediate object
Wrong. It's context is resolved in the scope of the currently executing function/environment.
Examples:
// global scope outside of any function:
let foo = {};
// Define a method in global scope (outside of any function)
foo.a = () => {
console.log(this); // undefined
}
// Return a function from scope of a method:
foo.b = function () {
// remember, "this" in here is "foo"
return () => {
console.log(this); // foo - because we are in scope foo.c()
}
}
foo.a(); // undefined
foo.b()(); // foo
For arrow functions, it is not what object the function belongs to that matters but where it is defined. In the second example, the function can completely not belong to foo but will still print foo regardless:
bar = {};
bar.b = foo.b();
bar.b(); // will log "foo" instead of "bar"
This is the opposite of regular functions which depend on how you call them instead on where you define them:
// Defined in global scope:
function c () {
console.log(this);
}
bar.c = c;
bar.c(); // will log "bar" instead of undefined because of how you call it
Note
Note that there are two very different concepts here that are intermingled - context (what value "this" has) and scope (what variables are visible inside a function). Arrow function uses scope to resolve context. Regular functions do not use scope but instead depend on how you call them.
Questions
Now to answer some of your questions:
In this case, what is the scope of this in fat arrow functions?
As I said. Scope and this are two unrelated concepts. The concept behind this is object/instance context - that is, when a method is called what object is the method acting on. The concept of scope is as simple as what are global variables and what variables exist only inside a specific function and it can evolve to more complicated concepts like closures.
So, since scope is always the same, the only difference is in arrow functions, its context (its this) is defined by the scope. That is, when the function is being declared, where is it declared? At the root of the file? Then it has global scope and this equals "undefined". Inside another function? Then it depends on how that function is called. If it was called as a method of an object such as UserSchema.methods for example if UserSchema.methods.generatePasswordSetter() returns an arrow function, then that function (let's call it setPassword()) will have it's this point to the correct object.
What is the scope, of this, in normal function definitions?
Based on my explanation above I can only sat that scope is not involved with the value of this in normal functions. For a more detailed explanation of how this works see my answer to this other question: How does the "this" keyword in Javascript act within an object literal?
How to access the object, in this case: UserSchema, properties (forgive me for less proper words) in fat arrow functions as one does in normal function definitions?
The way it's defined it is not possible. You need to define it from a regular function that has it's this pointing to UserSchema:
UserSchema.methods.generatePasswordSetter = function () {
return (password) => { /* implementation... */}
}
But this is probably not what you want. To do what you want you only need to stop using arrow functions in this case. Regular functions still exist for use-cases such as this.

How to implement inheritance in Node.JS

How do we use 'inheritance' in Node.JS? I heard that prototype is similar to interfaces in java. But I have no idea how to use it!
Although there are various ways of performing inheritance and OO in javascript, in Node.js you would typically use the built in util.inherits function to create a constructor which inherits from another.
See http://book.mixu.net/ch6.html for a good discussion on this subject.
for example:
var util = require("util");
var events = require("events");
function MyOwnClass() {
// ... your code.
}
util.inherits(MyOwnClass, events.EventEmitter);
Creating an object constructor in pure JS:
They're just functions like any other JS function but invoked with the new keyword.
function Constructor(){ //constructors are typically capitalized
this.public = function(){ alert(private); }
var private = "Untouchable outside of this func scope.";
}
Constructor.static = function(){ alert('Callable as "Constructor.static()"'); }
var instance = new Constructor();
Inheritance:
function SubConstructor(){
this.anotherMethod(){ alert('nothing special'); }
}
function SubConstructor.prototype = new Constructor();
var instance = new SubConstructor();
instance.public(); //alerts that private string
The key difference is that prototypal inheritance comes from objects, rather than the things that build them.
One disadvantage is that there's no pretty way to write something that makes inheritance of instance vars like private possible.
The whopping gigantor mega-advantage, however, is that we can mess with the prototype without impacting the super constructor, changing a method or property for every object even after they've been built. This is rarely done in practice in higher-level code since it would make for an awfully confusing API but it can be handy for under-the-hood type stuff where you might want to share a changing value across a set of instances without just making it global.
The reason we get this post-instantiated behavior is because JS inheritance actually operates on a lookup process where any method call runs up the chain of instances and their constructor prototype properties until it finds the method called or quits. This can actually get slow if you go absolutely insane with cascading inheritance (which is widely regarded as an anti-pattern anyway).
I don't actually hit prototype specifically for inheritacne a lot myself, instead preferring to build up objects via a more composited approach but it's very handy when you need it and offers a lot of less obvious utility. For instance when you have an object that would be useful to you if only one property were different, but you don't want to touch the original.
var originInstance = {
originValue:'only on origin',
theOneProperty:'that would make this old object useful if it were different'
}
function Pseudoclone(){
this.theOneProperty = "which is now this value";
}
Pseudoclone.prototype = originInstance;
var newInstance = new Psuedoclone();
//accesses originInstance.originValue but its own theOneProperty
There are more modern convenience methods like Object.create but only function constructors give you the option to encapsulate private/instance vars so I tend to favor them since 9 times out of 10 anything not requiring encapsulation will just be an object literal anyway.
Overriding and Call Object Order:
( function Constructor(){
var private = "public referencing private";
this.myMethod = function(){ alert(private); }
} ).prototype = { myMethod:function(){ alert('prototype'); };
var instance = new Constructor();
instance.myMethod = function(){ alert(private); }
instance.myMethod();//"undefined"
Note: the parens around the constructor allow it to be defined and evaluated in one spot so I could treat it like an object on the same line.
myMethod is alerting "undefined" because an externally overwritten method is defined outside of the constructor's closure which is what effective makes internal vars private-like. So you can replace the method but you won't have access to what it did.
Now let's do some commenting.
( function Constructor(){
var private = "public referencing private";
this.myMethod = function(){ alert(private); }
} ).prototype = { myMethod:function(){ alert('prototype'); };
var instance = new Constructor();
//instance.myMethod = function(){ alert(private); }
instance.myMethod();//"public referencing private"
and...
( function Constructor(){
var private = "public referencing private";
//this.myMethod = function(){ alert(private); }
} ).prototype = { myMethod:function(){ alert('prototype'); };
var instance = new Constructor();
//instance.myMethod = function(){ alert(private); }
instance.myMethod();//"prototype"
Note that prototype methods also don't have access to that internal private var for the same reason. It's all about whether something was defined in the constructor itself. Note that params passed to the constructor will also effectively be private instance vars which can be handy for doing things like overriding a set of default options.
Couple More Details
It's actually not necessary to use parens when invoking with new unless you have required parameters but I tend to leave them in out of habit (it works to think of them as functions that fire and then leave an object representing the scope of that firing behind) and figured it would be less alien to a Java dev than new Constructor;
Also, with any constructor that requires params, I like to add default values internally with something like:
var param = param || '';
That way you can pass the constructor into convenience methods like Node's util.inherit without undefined values breaking things for you.
Params are also effectively private persistent instance vars just like any var defined in a constructor.
Oh and object literals (objects defined with { key:'value' }) are probably best thought of as roughly equivalent to this:
var instance = new Object();
instance.key = 'value';
With a little help from Coffeescript, we can achieve it much easier.
For e.g.: to extend a class:
class Animal
constructor: (#name) ->
alive: ->
false
class Parrot extends Animal
constructor: ->
super("Parrot")
dead: ->
not #alive()
Static property:
class Animal
#find: (name) ->
Animal.find("Parrot")
Instance property:
class Animal
price: 5
sell: (customer) ->
animal = new Animal
animal.sell(new Customer)
I just take the sample code Classes in CoffeeScript. You can learn more about CoffeeScript at its official site: http://coffeescript.org/

How can I break this code up into two RequireJs modules

I've created the code below to dynamically load 2 buttons into an element with an ID of masthead. Then a function called showMenus runs when each button is clicked, running some jQuery animations. Everything is wrapped inside of a RequireJS module.
The code works fine as is but I'm thinking it may be better to break it up into two separate RequireJS modules/files: one that loads the buttons on the page and another one that runs the showMenus function. I did refer to the RequireJS API docs but couldn't find an answer.
Any help is appreciated...thanks in advance!
require(['jquery'], function ($) {
var header = document.getElementById("masthead"),
$navMenu = $("#site-navigation-list"),
$searchBox = $("#searchform"),
menuButton = document.createElement("div"),
searchButton = document.createElement("div"),
showMenus;
$(menuButton).attr("id", "menu");
$(searchButton).attr("id", "search");
header.appendChild(searchButton);
header.appendChild(menuButton);
// break the code below into its on RequireJS module?
showMenus = function(btn,el) {
$(btn).click(function() {
if (el.is(":visible") ) {
el.slideUp({
complete:function(){
$(this).css("display","");
}
});
} else {
el.slideDown();
}
});
};
showMenus(menuButton, $navMenu);
showMenus(searchButton, $searchBox);
});
What follows is only my opinion, but you might find it useful.
It might help to think in terms of things that your app is made of, and then maybe they are candidates for modules. So in your example, a 'masthead' seems to be a thing that you are interested in.
So using RequireJS, we can create a new module representing a generic masthead:
// Masthead module
define(['jquery'], function ($) {
function showMenus (btn, el) {
function toggle (el) {
if (el.is(":visible")) {
el.slideUp({
complete:function(){
$(this).css("display","");
}
});
} else {
el.slideDown();
}
}
$(btn).click(function() {
toggle(el);
});
}
// A Masthead is an object that encapsulates a masthead DOM element.
// This is a constructor function.
function Masthead (mastheadElement) {
// 'this' is the masthead object that is created with the 'new'
// keyword in your application code.
// We save a reference to the jQuerified version of mastheadElement.
// So mastheadElement can be a DOM object or a CSS selector.
this.$mastheadElement = $(mastheadElement);
}
// Add a method to Masthead that creates a normal button
Masthead.prototype.addButton = function (id) {
var $btn = $("<div/>").attr("id", id);
this.$mastheadElement.append($btn);
return $btn;
};
// Add a method to Masthead that creates a 'toggling' button
Masthead.prototype.addTogglingButton = function (id, elementToToggle) {
// ensure we have a jQuerified version of element
elementToToggle = $(elementToToggle);
// Reuse the existing 'addButton' method of Masthead.
var $btn = this.addButton(id);
showMenus($btn, elementToToggle);
return $btn;
};
// return the Masthead constructor function as the module's return value.
return Masthead;
});
And then use this module in our actual application code:
// Application code using Masthead module
require(["Masthead"], function (Masthead) {
// We create a new Masthead around an existing DOM element
var masthead = new Masthead("#masthead");
// We add our buttons.
masthead.addTogglingButton("menu", "#site-navigation-list");
masthead.addTogglingButton("search", "#searchform");
});
The advantage of this approach is that no DOM ids are hard-coded into the module. So we can reuse the Masthead module in other applications that require this functionality, but which may be using different DOM ids.
It might be convenient to think of this as separating the what things are from the how we use them.
This is a simple example, but frameworks/libraries like Backbone and Dojo (and many, many more) take this further.

Resources