require() not working with variable - react native - javascript

I meet a weird problem. If I set a variable direclty with a value like this "const myString = 'someWord';" that work but if I take the value from a variable like this "const myString = someVariable;", that doesn't work, and if I set the value on a conditional block that doesn't work too.
So, work:
var jsonName = 'tramwayen';
const pathex = require('../assets/JSON/' + jsonName);
var json = JSON.parse(JSON.stringify(pathex));
doesn't work:
var jsonName = variable;
const pathex = require('../assets/JSON/' + jsonName);
var json = JSON.parse(JSON.stringify(pathex));
doesn't work:
var jsonName = '';
if (condition) {
jsonName = 'tramwayen';
}
const pathex = require('../assets/JSON/' + jsonName);
var json = JSON.parse(JSON.stringify(pathex));
I really don't understand.
I have this error :
"Invalid call at line 41: require('../assets/JSON/' + jsonName2)"

Most JS bundlers cannot handle dynamic require imports. You might want to load all of the files, and put them in an object:
let data = {
tramwayen: require('../assets/JSON/tramwayen.json'),
something: require('../assets/JSON/something.json'),
// and so on
};
And use the data object to retrieve the data you need.

From what I read while doing some research, it seems impossible to made a require dynamically. In react native require should be static.
But there are some solutions to avoid this issue.
Here is mine, I put all data of my differents Json on one single json, and I dynamically choice wich part of the data I want to get.
I can also, put all the static require on an object, and choose dynamicaly wich require I want to get.
solution 1:
const id = window.currentPI;
const json = require('../assets/JSON/mainData.json');
const nbreOfPix = json[`${id}`].preData.numberOfPictures;
solution 2:
const IMAGES = {
tramwayen: require('../assets/CtrlPI/PHOTO_articles/008_02_Img.png'),
tramwayen2: require('../assets/CtrlPI/PHOTO_articles/HC002_04_Img.png')
};
getImage = (name) => {
return IMAGES[name];
};

Related

How can I extract alternative names data from a CSR?

I have a CSR and I can parse all the data with pkijs.org lib, but I have no luck to parse alternative names data. How is it possible to do with a javascript? Some other libs can be in use, I guess, do you know one?
Following the docs of CertificationRequest class provided by pkijs here https://pkijs.org/docs/classes/CertificationRequest.html. We can see that the structure of a CSR. The subject alternative name will be stored in attributes propery of CertificationRequest object. But the structure inside of attributes is quite complex to make it as plain text. This is my code used to print out the subject alternative name
const pkijs = require('pkijs');
const utils = require("pvtsutils");
const asn1js = require("asn1js");
let base64 = "<your_csr_in_base64>"
let csrraw = utils.Convert.FromBase64(base64);
console.log(csrraw)
const pkcs10 = pkijs.CertificationRequest.fromBER(csrraw);
let seq = pkcs10.attributes[0].values[0];
let exts = pkijs.Extensions.fromBER(seq.toBER(false));
console.log(exts);
var san = getExtentionsForSANFromExtensions(exts);
console.log(san)
if (san != undefined) {
san.names.forEach(element => {
console.log(element.type + " = " + element.value)
});
}
function getExtentionsForSANFromExtensions(exts){
for (var i = 0 ; i< exts.extensions.length; i++) {
var ext = exts.extensions[i];
if(ext.extnID == '2.5.29.17') {
var octetString = asn1js.fromBER(ext.extnValue.toBER(false)).result;
return pkijs.GeneralNames.fromBER(octetString.getValue());
}
}
}
I've tested this code and it works properly with CSR generated by Keystore Explorer. Have not tested with another tool to generate CSR that supports subject alternative names.
Cheers!
If you have a CSR and need to extract the alternative names data from it, you can use the following command:
openssl req -in csr.pem -noout -text
This will print out the entire CSR, including the alternative names data.

How to pass dictionary inside template literal in JS

How do I pass the whole dictionary inside the template literal?
Here is my code:
var pvtInPlan = treatmentPlan.pavementIDs;
var pcrAfterPlan = treatmentPlan.pavementCondition;
var yearlyPlan = {};
pvtInPlan.forEach((key, i) => yearlyPlan[key] = pcrAfterPlan[i]); // I want to pass this yearlyPlan
var arcadeExpression = `
var plan = ${yearlyPlan};
var pvtID = 100;
return plan[pvtID]`; // I want to be able to return such statement.
Whenever I use 'var plan = ${yearlyPlan};' line, it throws me error. It works when I use 'var plan = ${yearlyPlan[100]};' directly. But I need to pass index to this dictionary from inside of template literal.
I would be glad if someone could help me with this.
Thanks!
You can just do a simple JSON.stringify if u want to dump the entire content, for example:
const yearlyPlan = JSON.stringify({ key1: 'content', key2: 'content2' })
const arcadeExpression = `
var plan = ${yearlyPlan};
var pvtID = 100;
return plan[pvtID]`; // I want to be able to return such statement.
console.log(arcadeExpression)
>>>
"var plan = {"key1":"content","key2":"content2"};
var pvtID = 100;
return plan[pvtID]"
If you want a more customized version, then u would need to access each key-value pair to format the message.

How to get json data with vars in p5.js

I'm building a dictionary word definition search engine which has a #submit button and #word input. I also have a JSON dictionary(Github link). I don't know how to select what word definition to use depending on what the user types.
I have already tried putting the input.value() as a var to the json object query:
var uInVal = input.value();
document.getElementById("p1").innerHTML = words.uInVal)
Can someone help me?
My Code:
var words;
var input;
function setup() {
loadJSON("dictionary.json", gotData);
var button = select('#submit');
button.mousePressed(keyDraw);
input = select('#word');
}
function gotData(data){
words = data;
}
function keyDraw(){
document.getElementById("p1").innerHTML; //This is where the word definition should get printed
}
In the future, please try to work with a simpler example. Something like this would show your problem in a runnable example:
var jsonString = '{"x": 42, "y":100}';
var jsonObject = JSON.parse(jsonString);
This is also easier for you to work with. Now that you have this, I'd google something like "javascript get value from property name" for a ton of results.
But basically, there are two ways to get the value of a property:
var xOne = jsonObject.x;
var xTwo = jsonObject['x'];
console.log(xOne);
console.log(xTwo);
This is what you're trying to do:
var varName = 'x';
var myX = jsonObject.varName;
This won't work, because jsonObject doesn't have any field named varName. Instead, you want to access the x field. To do that, you can use bracket [] notation:
var myX = jsonObject['x'];

Javascript objects matching

A Javascript object can be used as an associative array.
So my question is how can I automatically set that multiple key's with the same ending match one value?
I'll write an example to be more explicit on what I want.
Something like this:
var handle = {}
handle[*css] = handlers.style;
Every key that ends with "css" should be matched to handlers.style.
Any way to doing this?
PD: Im doing this with server-side javascript with NodeJS
This is possible if you iterate through the object properties and check that the property name matches the desired pattern. Something like:
for (var i in obj) {
if (i.toString().substr(-3) === 'css') {
obj[i] = handlers.style;
}
}
A quick and dirty way:
var handle = {}
name = "article_users_css"
handle[name.substr(name.length-3)] = "something"
or if you can use some symbol to delimit the suffix, you can use this instead:
name.substr(str.lastIndexOf(YOUR_CHAR_OF_CHOICE))
I don't think you can do this. But you can the request pathname before routing the request to your handlers.
See example below:
var path = "mystyle.css"
// var path = "index.html"
// var path = "image.png"
var handle = {};
handle[css] = handlers.style;
handle[html] = handlers.html;
handle[img] = handlers.img;
if (path.match(/.*\.css/)) {
handle[css]();
}
else if (path.match(/.*\.html/)) {
handle[html]();
}
else if ((path.match(/.*\.png/) || path.match(/.*\.jpg/)) {
handle[img]();
}
You can consider using Express that does support routing based on regEx matching

Get Query String with Dojo

Users will be hitting up against a URL that contains a query string called inquirytype. For a number of reasons, I need to read in this query string with javascript (Dojo) and save its value to a variable. I've done a fair amount of research trying to find how to do this, and I've discovered a few possibilities, but none of them seem to actually read in a query string that isn't hard-coded somewhere in the script.
You can access parameters from the url using location.search without Dojo Can a javascript attribute value be determined by a manual url parameter?
function getUrlParams() {
var paramMap = {};
if (location.search.length == 0) {
return paramMap;
}
var parts = location.search.substring(1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
Then you could do the following to extract id from the url /hello.php?id=5&name=value
var params = getUrlParams();
var id = params['id']; // or params.id
Dojo provides http://dojotoolkit.org/reference-guide/dojo/queryToObject.html which is a bit smarter than my simple implementation and creates arrays out of duplicated keys.
var uri = "http://some.server.org/somecontext/?foo=bar&foo=bar2&bit=byte";
var query = uri.substring(uri.indexOf("?") + 1, uri.length);
var queryObject = dojo.queryToObject(query);
//The structure of queryObject will be:
// {
// foo: ["bar", "bar2],
// bit: "byte"
// }
In new dojo it's accessed with io-query:
require([
"dojo/io-query",
], function (ioQuery) {
GET = ioQuery.queryToObject(decodeURIComponent(dojo.doc.location.search.slice(1)));
console.log(GET.id);
});
Since dojo 0.9, there is a better option, queryToObject.
dojo.queryToObject(query)
See this similar question with what I think is a cleaner answer.

Categories