Node js : How to access local variable between the methods [duplicate] - node.js

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 5 years ago.
first();
function first(){
second();
third();
}
function second(){
var b='second';
}
function third(){
console.log(b);
}
Getting error while trying to access variable b in third(), can you please help
console.log(b);
^
ReferenceError: b is not defined

if you want to access b than you have to define it as global
first();
var b;
function first(){
second();
third();
}
function second(){
b='second';
}
function third(){
console.log(b);
}
console.log(b);
look my bin global b

Related

How to use environment variable in Typescript properly? [duplicate]

This question already has answers here:
using process.env in TypeScript
(19 answers)
Closed 1 year ago.
I'm trying to make a simple api using typescript and when I use any env variable I get an error from TS compiler Tells me that this could be undefined
example
// Not Working
const db = process.env.DB_URL // This gives an error that the result could be a string or undefined
to fix this
I have to make a type guard and check with if statement as follows
const db = process.env.DB_URL
if (db){
// ....
}
Is there a better approach to to such a thing instead of explicitly check for every variable ?
You can apply null check and keep it as string instead of defining two types:
const db: string = process.env.DB_URL ?? ''
// empty strings are falsy/falsey
if (db) { // do this}
else { //do this}

How do you access the directory that your module is in? [duplicate]

This question already has answers here:
How do I get the path to the current script with Node.js?
(15 answers)
Closed 3 years ago.
If you have a module that's being imported in some code, let's say...
var my_cool_module = require('my_directory/my_cool_module');
my_cool_module.print_directory_name();
And I'm in that module's context, say this is the file my_cool_module.js...
function get_dir_name() {
// get the directory name...
return directory_name;
}
exports.module.print_directory_name = function() {
console.log("This module is in directory " + get_dir_name());
};
How can I get the directory that the module is in (i.e. "my_directory")
I found out from the node.js documentation here that you can use __dirname
function get_directory_name() {
return __dirname;
}

How to use removeAtIndex if var parameter is deprecated [duplicate]

This question already has answers here:
'var' parameters are deprecated and will be removed in Swift 3
(8 answers)
Closed 6 years ago.
I am using a var for IPAddress, for which i wanted to remove trailing slash (/). Now i see a warning that 'var' is deprecated. In such case how can i use removeAtIndex method in new style?
if ipAddress.characters.last == "/" {
ipAddress.removeAtIndex(ipAddress.endIndex.predecessor())
}
Remove var from the function parameter declaration and then create a mutable copy:
func myFunc(ipAddress: String) { // remove the var if you write here var ipAddress
var ipAddress = ipAddress
// change ipAddress here
}
var is only deprecated in function arguments.
See here the original change request:
https://github.com/apple/swift-evolution/blob/master/proposals/0003-remove-var-parameters.md

Defining modules in UI5

I am trying to keep my code separated in modules. When I defined my first module I extended sap.ui.base.Object and it worked. My question is: Is it a must to extend sap.ui.base.Object when defining my own module? According to the API documentation I tried following example:
sap.ui.define([], function() {
// create a new class
var SomeClass = function();
// add methods to its prototype
SomeClass.prototype.foo = function() {
return "Foo";
}
// return the class as module value
return SomeClass;
});
I required this module inside my Component.js as dependency like this:
sap.ui.define([
"path/to/SomeClass"
], function (SomeClass) {
"use strict";
//var test = new SomeClass();
I always receive a syntax error:
failed to load '[...]/Component.js' from ./Component.js: Error: failed to load '[...]/module/SomeClass.js' from ./module/Service.js: SyntaxError: Unexpected token ;
Does anyone have an idea why this happens? Thanks!
We group code in modules like this for example:
jQuery.sap.declare("our.namespace.iscool.util.Navigation");
our.namespace.iscool.util.Navigation = {
to: function (pageId, context) {
// code here
}
// etc.
}
and call the function of the module like this in a controller
jQuery.sap.require("our.namespace.iscool.util.Navigation");
sap.ui.controller("our.namespace.iscool.Detail", {
// somewhere in this file comes this
handleNavButtonPress: function (evt) {
our.namespace.iscool.util.Navigation.navBackToMaster(
evt.getSource().getBindingContext()
);
},
}
Stupid mistake - missing curly brackets in the docs.
var someclass = function() {} ;

Differences between nodejs modules and their exports [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I was just browsing through the nodejs source and noticed differences between the ways different modules are exported. For example, some modules export an object with a prototypical inheritance style:
Thing = function () {
constructor stuff
}
Thing.prototype.jump () {
jump stuff
}
exports = Thing
Where as other modules will append functions directly to exports:
exports.spectacles = function () {
spectacle stuff
}
To me it seems that they will achieve similar goals, but they are clearly different. I believe the first example describes something like an a class, whereas the second simply makes available static methods.
What are the fundamental differences between these two approaches, how are they properly described and what are the advantages/disadvantages of one over the other?
Try viewing this from another perspective: the module which requires your module.
Each file in Node is a module. Each module has a global var, module, and it's property, exports. Whatever you put on that exports property will be available as the module's export.
Primitive
Ie. a boolean, number or a string will work:
module.exports = 3;
When you require that file, you'll get '3'.
var myModule = require('./my-module');
console.log(myModule); // <== 3
But since everything in JavaScript is an object, then you can call methods even a primitive prop:
console.log(myModule.toString()); // <== "3"
Function
You can also export a function.
module.exports = function() {
console.log('3 more');
};
That export will be a function:
var myModule = require('./my-module');
myModule(); // <== '3 more'
Of course, a function is also an object, so you have methods on that too to try out.
console.log(myModule.toString());
// You get: 'function (){\n console.log(\'3 more\');\n }'
Object
Then you can export an object with a few of those things:
module.exports = {
prop: 3,
method: function() {
console.log('Not 3 this time.');
}
};
When you require this module, you'll have that object - an object with a property prop and a method method.
var myModule = require('./my-module');
console.log(myModule.prop); // <== 3
myModule.method(); // <== 'Not 3 this time'
So you get the pattern? Whatever you put in module.exports is what you get on the other end. A matter of perspective, as I've said.
Default
Even if you don't export anything (ie. require an empty file), you have an export.
Require an empty file (it has to exist tho
var myModule = require('./my-module');
console.log(myModule); // <== {}
This tells you that the default export is an empty object.
This is where it gets interesting.
If module.exports = {} by default, then if we simply attach to it, we can add props to it:
So, when Node first gets your module (file), it's a {}. We can simply attach props to it.
module.exports.prop = 3;
module.exports.method = function() { console.log('I am out of ideas for placeholders, I should use kitten');}
Why does it work without the module keyword?
Now, why does this work without the module keyword? Ie. just:
exports.prop = 3;
exports.method = function() {};
Because when the Node.js starts working your file, it aliases exports to module.exports. But be careful, you can override this!
What does that mean? It's almost as if you wrote var exports = module.exports at the beginning of the file.
So you can use just the exports syntax, but I prefer not to. Why? Because you can make a mistake and override exports var. And you'll be more careful with module.exports. (There are other reasons, this one is what I have learned about first and remembered best.)
Example 1:
exports.prop = false;
// later in module
module.exports = myObj; // see? overriden.
Example 2:
var exports = {}; // see? Overridden default module.exports.
exports.prop = 4;
exports.method = function(){
console.log('3 more');
};
So when you require this later:
var myModule = require('./my-module');
console.log(myModule); // <== {}
I hope this helps.
The differences that you are pointing out are mainly flavour based. It is very related with how people prefer to construct their objects.
Javascript has lot's of different ways to build objects, here is another example:
exports.stuff = {
f1: function() ...
foobar: function() ...
}
For example, I prefer to wrap everything with a function to enforce use strict and simulate static variables:
(function() {
"use strict";
var staticVariable;
function MyObject() {
...
};
exports.MyObject = MyObject;
})();
+1 on close vote. This question is very subjective.

Resources