How do I search an object full of strings in node js? - node.js

I'm new to node js programming and I have the following :
var myObj = {
AD: '{+376}',
AF: '{+93}',
AG: '{+1268}'
};
NOTE: I cannot modify this object data, as it comes from a third party component. I have only put an example of what data is returned to me in a local object for debugging purposes.
I'd like to be able to search this object for "AD" and pull out just the +376 from this line
"AD": "{+376}"
this does not seem to work:
var i = myObj.indexOf("AD");
console.log(i);
UPDATE
Sorry... I was using stringify on the object and the output I was seeing in the terminal window was wrong... I have corrected the question
UPDATE again
OK... running it using myObj works in a local sandbox... but using it on the actual data that comes back from the NPM object does not. Here is a RunKit:
https://npm.runkit.com/country-codes-list
This code does returns the number...
var ccl = require("country-codes-list")
var l = ccl.customList('countryCode', '+{countryCallingCode}');
console.log(l.AD);
BUT I need a variable instead of .AD like this:
var ad = 'AD'
var ccl = require("country-codes-list")
var l = ccl.customList('countryCode', '+{countryCallingCode}');
console.log(l.ad); // doesn't work !

This should work.
var ad = 'AD'
var ccl = require("country-codes-list")
var l = ccl.customList('countryCode', '+{countryCallingCode}');
console.log(l[ad]);

You can use the key to reach for the value.
var string = '{"AD":"{+376}","AF":"{+93}","AG":"{+1268}"}';
var object = JSON.parse(string);
function search(id) {
return object[id];
}
console.log(search('AD')) //--> {+376}

Related

Reference error! Not defined using node.js / Runkit

I'm trying to use this https://npm.runkit.com/globalpayments-api script but I can't figure what I'm doing wrong.
When I run the Runkit and add the first code to create a new Credit Card it throws error "ReferenceError: CreditCardData is not defined":
const card = new CreditCardData();
card.number = "4111111111111111";
card.expMonth = "12";
card.expYear = "2025";
card.cvn = "123";
How I can point CreditCardData to var globalpaymentsApi = require("globalpayments-api") which contains all this consts?
Demo: https://runkit.com/embed/8hidbubpbk8n
What I'm doing wrong?
Most likely in your code, function CreditCardData() doesn't exist - this means you didn't import it. Try adding this at the beginning of your .js file:
const { CreditCardData } = require('globalpayments-api');

Moment.js: "TypeError: momentRange.range" when using with moment-range

I have problem using all 3 of the packages together. I define them like this:
var moment = require('moment-timezone');
var momentRange = require('moment-range');
And when I want to use the moment-range functions, I'm trying to call it like this:
var range1 = momentRange.range(moment("string1"), moment("string2"));
And I'm getting error: TypeError: momentRange.range is not a function
What am I doing wrong?
According to the documentation, you are supposed to use the moment-range library to first extend the core moment library itself, then use moment.range because the moment-range package adds additional functions to the moment object:
var momentRange = require('moment-range');
momentRange.extendMoment(moment);
moment.range(moment(…), moment(…)); // Now usable
Specifically, in their documentation:
CommonJS:
const Moment = require('moment');
const MomentRange = require('moment-range');
const moment = MomentRange.extendMoment(Moment);

Using a helper class easily in expressjs

I'm using a pretty barebones expressjs app and want to add a library/helper to store some useful code. Ideally, I'd like it to work as a module. However, I'm unable to get it to work. Here's what I've got:
// helpers/newlib.js
var NewLib = function() {
function testing() {
console.log("test");
}
};
exports.NewLib = NewLib;
.
// controllers/control.js
var newlib = require('../helpers/newlib').NewLib;
var helper = new NewLib();
helper.testing();
.
The error I get is ReferenceError: NewLib is not defined. I followed the design pattern (of how exports works) based on another simple module I downloaded.
What am I doing wrong?
There are two problems with your code.
First, you are assigning the NewLib function from helpers/newlib.js to newlib var, so you should use new newlib() not new NewLib():
// controllers/control.js
var newlib = require('../helpers/newlib').NewLib;
var helper = new newlib(); // <--- newlib, not NewLib
helper.testing();
Or you can rename your variable to NewLib:
// controllers/control.js
var NewLib = require('../helpers/newlib').NewLib;
var helper = new NewLib(); // <--- now it works
helper.testing();
Second, the testing function is not accessible outside the constructor scope. You can make it accessible by assigning it to this.testing for instance:
// helpers/newlib.js
var NewLib = function() {
this.testing = function testing() {
console.log("test");
}
};

How to load types in the System namespace with Mono.Cecil?

I'm using Mono.Cecil (0.9.5.4) to inject code into some of my assemblies. Some of the calls I need to make are to objects in the System.ComponentModel namespace. How can I find those 'MethodReferences' that I need to call?
What I tried:
AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly(dllPath);
var objectModelRef = assembly.MainModule.AssemblyReferences.First(i => i.Name == "System.ObjectModel")
var objectModelAssembly = assembly.MainModule.AssemblyResolver.Resolve(objectModelRef);
But then objectmodelAssembly.MainModule.Types has no actual types in it.
I also tried this:
AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly(dllPath);
var system = new DefaultAssemblyResolver().Resolve("System");
var objectIWantToInject = assembly.MainModule.Import(FindType(...));
This works fine on a machine with the full .net 4.5 installed. But since my assembly is a PCL, when I try executing on WinPhone, I get FileNotFound for 'System'.
So if I wanted to get an instance of TypeDefinition for System.ComponentModel.ProgressChangedEventArgs that I could then make calls to some of the methods on, how would I?
In your code:
AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly(dllPath);
var system = new DefaultAssemblyResolver().Resolve("System");
var objectIWantToInject = assembly.MainModule.Import(FindType(...));
I think you are missing at least one import, e.g.
assembly.MainModule.Import(typeof(System.ObjectModel);
I believe you will also need to "Resolve" it to walk further down the tree.
Here is a working sample for anyone that is feeling the same pain:
assembly.MainModule.Import(typeof(string));
var methodBaseRef = assembly.MainModule.Import(typeof(System.Reflection.MethodBase));
var getMemberInfo = assembly.MainModule.Import(typeof(System.Reflection.MemberInfo));
var getMemberInfoResolver = getMemberInfo.Resolve();
var getCurrentMethodRef = assembly.MainModule.Import(typeof(System.Reflection.MethodBase).GetMethod("GetCurrentMethod"));
var get_DeclaringType = assembly.MainModule.Import(getMemberInfoResolver.Methods.Single(m => m.Name == "get_DeclaringType"));
var getTypeInfo = assembly.MainModule.Import(typeof(Type));
var name = assembly.MainModule.Import(typeof(Type).GetMethod("Name"));

Unexpected value for 'this' in express.js instantiated controllers

'this' does not appear to refer to the instantiated budget controller object. Instead it seems to refer to the global object. Does anyone know why this is?
I've defined a budget model. Injected into the controller and I'm attempting to simply generate a random 6 char string when I hit /budgets in my app. Instead this.DEFAULT_SLUG_LENGTH is undefined and I can't figure out why.
This is a dumbed down test case illustrating the issue with 'this'. I have a similar problem when referencing the injected this.budget within another function to query the db based on the slug value.
//models/budget.js
var Schema = require('jugglingdb').Schema;
var schema = new Schema('postgres',{url:process.env.DATABASE_URL});
var Budget = schema.define('budgets',{
total: Number,
slug: String
});
module.exports = Budget;
====================
//controllers/budget.js
function BudgetController (budget) {
this.budget = budget;
};
BudgetController.prototype.DEFAULT_SLUG_LENGTH = 6;
BudgetController.prototype.generateSlug = function (req,res) {
var slug = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < this.DEFAULT_SLUG_LENGTH; i++) {
slug += possible.charAt(Math.floor(Math.random() * possible.length));
}
res.send(slug);
};
module.exports = BudgetController;
===================
//app.js
var express = require('express');
var app = express();
app.use(express.bodyParser());
// models
var Budget = require('./models/budget');
// controllers
var BudgetController = require('./controllers/budget');
var budgetCtrl = new BudgetController(Budget);
// routes
app.get('/budgets',budgetCtrl.generateSlug);
app.listen(process.env.PORT || 4730);
If I manually instantiate the model/controller in the node repl, the generateSlug method works fine. If I restructure my code so that the BudgetController is a function that returns an object {} with methods, that seems to work fine. Is there some issue with my use of prototype/new ?
express takes functions and invokes them without a preceding object, so if you want to use an object method bound to a specific this as an express route handler function, you need to bind it:
app.get('/budgets', budgetCtrl.generateSlug.bind(budgetCtrl));

Resources