Nodejs splitting string - javascript

let NewName= params.strdocumentname + "(" + results.rows[0].arrayfilecount+ ")";
strdocumentname = params.strdocumentname = NewName;
the current output is Jayson.png(2)
desired output Jayson (2).png
How do i do that using the code above?

Use the following code:-
const path = require('path');
const extension= path.extname(params.strdocumentname);
const name= params.strdocumentname.replace(extension,"(" + results.rows[0].arrayfilecount+ ")");
const newName = name + extension;
Hope it helps
Thanks

I think your params.strdocumentname contains the extension of the file also.
Try this code;
let [fileName, extension] = params.strdocumentname.split('.');
let NewName= fileName + "(" + results.rows[0].arrayfilecount+ ")." + extension;
strdocumentname = params.strdocumentname = NewName;
see working fiddle
let mockFileName = "abc.png"
let mockArrayCount = '1'
let [fileName, extension] = mockFileName.split('.');
let NewName= fileName + "(" + mockArrayCount+ ")." + extension;
console.log(NewName)
alert(NewName)

Related

Safari downloads vcf as example.com javascript

I am trying to generate a vCard .vcf file and download it on click. It works perfectly for all browsers except Safari. On safari, it downloads example.com instead of the proper file. I read a lot about the Safari download attribute issue, but it seems this is not the problem in my case. Any help would be highly appreciated.
This is my crappy code :)
let vCard = document.querySelector('.vcard')
let vcard_start ="BEGIN:VCARD\nVERSION:3.0\n"
let vcard_end = "END:VCARD"
let fullName = document.querySelector('#fullname').innerText
//let firstName = document.querySelector('#firstname').innerText
//let lastName = document.querySelector('#lastname').innerText
let title = document.querySelector('#title').innerText
let email = document.querySelector('#email').innerText
let phone = document.querySelector('#phone').innerText
let address = document.querySelector('#address').innerText
let vcard_download = document.querySelector('#vcard-download')
let currentURL = window.location.href
let attPhoto = document.querySelector('#att_image')
let attPhotoSRC = attPhoto.querySelector('img').src
let splitName = fullName.split(' ')
//let vCardPhoto =
//const space = split(/\r?\n/);
let vcardReady
let newName
if(splitName.length>=3){
newName = splitName[2] + ';' + splitName[0] + ' ' + splitName[1]
}else{
newName = splitName[1] + ';' + splitName[0]
}
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href','data:text/vcard;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
let base64_image_encoded;
window.addEventListener('load',function(){
// Start file download.
vcard_download.addEventListener("click", function(){
const tmp = base64_image_encoded.split(",");
// Generate download of vCard file with some content
vcardReady = vcard_start+
"FN:"+fullName+ "\n" +
"N:" + newName + "\n" +
"EMAIL:" + email + "\n" +
"ORG:Carella, Byrne, Cecchi, Brody & Agnello, P.C\n" +
"ROLE:" + title + "\n" +
"TEL;TYPE=WORK;VOICE:" + phone + "\n" +
"URL:" + currentURL + "\n" +
"PHOTO;TYPE=JPEG;ENCODING=BASE64:"+ tmp[1] + "\n" +
"NOTE;CHARSET=us-ascii;ENCODING=QUOTED-PRINTABLE:" + "\n" +
vcard_end;
var text = vcardReady;
var filename = fullName+'.vcf';
download(filename, text);
});
toDataURL(attPhotoSRC, function (dataUrl) {
base64_image_encoded = dataUrl;
});
});
function toDataURL(src, callback, outputFormat) {
let image = new Image();
image.crossOrigin = 'Anonymous';
image.onload = function () {
let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
let dataURL;
canvas.height = this.naturalHeight;
canvas.width = this.naturalWidth;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
};
image.src = src;
if (image.complete || image.complete === undefined) {
image.src = "data:image/gif;base64, R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
image.src = src;
}
return image;
}
I have seen this issue when there was a newline character in the filename for Safari. Removing that newline did the trick for me

Insert a character before the file or .(extension)

I wanted to insert the prefix before the file extention.
#Sample filename
DOC.doc
#code
let filename = "Doc.doc"
const prefix = Date.now().toString();
filename += prefix;
#Desired output (1595214202266 is the prefix.)
DOC-1595214202266.doc
Just split the fileName on "." and concat the prefix to file and make the string.
const prefix = Date.now().toString();
var fileName = "DOC.doc"
var [name, ext] = fileName.split('.');
console.log(`${name}-${prefix}.${ext}`)
let filename = "Doc.doc"
const prefix = Date.now().toString();
let extensionIndex = filename.indexOf(".");
filename = filename.substr(0,extensionIndex) + "-" +
prefix + filename.substr(extensionIndex,filename.length);
console.log(filename);

AWS IoT: Subscribe to Topic in Browser

I'm currently developing a Serverless App with AWS.
I want to subscribe to a topic using plain JavaScript (No Node.js, React, Angular etc.)
The IoT and IoTData SDK's doesn't support a "subscribe to topic" function.
To achieve this, i need to implement the aws-iot-device sdk, via require('aws-iot-device') (which i can't use in plain JS).
Unfortunatly this SDK only works with runtimes like Node.js or Browserify.
So how can someone subscribe to a topic from browser? Is there a way to implement the SDK into plain JS?
Thanks in advance
This is how its done, works perfectly fine:
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/components/core-min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/components/hmac-min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/components/sha256-min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>
cp this libaries into your html.
function SigV4Utils(){}
SigV4Utils.sign = function(key, msg) {
var hash = CryptoJS.HmacSHA256(msg, key);
return hash.toString(CryptoJS.enc.Hex);
};
SigV4Utils.sha256 = function(msg) {
var hash = CryptoJS.SHA256(msg);
return hash.toString(CryptoJS.enc.Hex);
};
SigV4Utils.getSignatureKey = function(key, dateStamp, regionName, serviceName) {
var kDate = CryptoJS.HmacSHA256(dateStamp, 'AWS4' + key);
var kRegion = CryptoJS.HmacSHA256(regionName, kDate);
var kService = CryptoJS.HmacSHA256(serviceName, kRegion);
var kSigning = CryptoJS.HmacSHA256('aws4_request', kService);
return kSigning;
};
function createEndpoint(regionName, awsIotEndpoint, accessKey, secretKey) {
var time = moment.utc();
var dateStamp = time.format('YYYYMMDD');
var amzdate = dateStamp + 'T' + time.format('HHmmss') + 'Z';
var service = 'iotdevicegateway';
var region = regionName;
var secretKey = secretKey;
var accessKey = accessKey;
var algorithm = 'AWS4-HMAC-SHA256';
var method = 'GET';
var canonicalUri = '/mqtt';
var host = awsIotEndpoint;
var credentialScope = dateStamp + '/' + region + '/' + service + '/' + 'aws4_request';
var canonicalQuerystring = 'X-Amz-Algorithm=AWS4-HMAC-SHA256';
canonicalQuerystring += '&X-Amz-Credential=' + encodeURIComponent(accessKey + '/' + credentialScope);
canonicalQuerystring += '&X-Amz-Date=' + amzdate;
canonicalQuerystring += '&X-Amz-SignedHeaders=host';
var canonicalHeaders = 'host:' + host + '\n';
var payloadHash = SigV4Utils.sha256('');
var canonicalRequest = method + '\n' + canonicalUri + '\n' + canonicalQuerystring + '\n' + canonicalHeaders + '\nhost\n' + payloadHash;
var stringToSign = algorithm + '\n' + amzdate + '\n' + credentialScope + '\n' + SigV4Utils.sha256(canonicalRequest);
var signingKey = SigV4Utils.getSignatureKey(secretKey, dateStamp, region, service);
var signature = SigV4Utils.sign(signingKey, stringToSign);
canonicalQuerystring += '&X-Amz-Signature=' + signature;
canonicalQuerystring += '&X-Amz-Security-Token=' + encodeURIComponent(AWS.config.credentials.sessionToken);
return 'wss://' + host + canonicalUri + '?' + canonicalQuerystring;
}
var endpoint = createEndpoint(
'eu-central-1', // YOUR REGION
'xxxxxx.iot.eu-central-1.amazonaws.com', // YOUR IoT ENDPOINT
accesskey, // YOUR ACCESS KEY
secretkey); // YOUR SECRET ACCESS KEY
var clientId = Math.random().toString(36).substring(7);
var client = new Paho.MQTT.Client(endpoint, clientId);
var connectOptions = {
useSSL: true,
timeout: 3,
mqttVersion: 4,
onSuccess: subscribe
};
client.connect(connectOptions);
client.onMessageArrived = onMessage;
client.onConnectionLost = function(e) {
console.log(e)
};
function subscribe() {
client.subscribe("my/things/something");
console.log("subscribed");
}
function onMessage(message) {
var status = JSON.parse(message.payloadString);
}
With this code, you can subscribe to IoT Topics in plain client side JavaScript. No Node.js, React.js or similar is needed!
You can use paho js or mqttjs in the browser. The aws-iot-device sdk for javascript is a wrapper around mqttjs.

AWS Signing and Javascript

I need to send HTTP request to AWS with signed request via Javascript. Sadly I cannot use the AWS SDK JS as its either for Node.js or browser, but I need to run it from Rhino JS environment.
seems I am doing something very wrong as I get whatever I do same result - AWS was not able to validate the provided access credentials.
:(
The code I am using is same as the one Amazons is using as example (but in Python). I am using only one external lib so I can use HMCA &SHA.
Any help is much appreciated (and needed as I am struggling for days by now...), so yeah - help!
Thanks is advance!
Cheers,
Joro
gs.include('jshashes');
var method = 'GET';
var service = 'ec2';
var host = 'ec2.amazonaws.com';
var region = 'us-east-1';
var endpoint = 'https://ec2.amazonaws.com';
var access_key = 'ACCESSKEY';
var secret_key = 'SECRET/KEY';
var request_parameters = 'AWSAccessKeyId' + access_key + 'Action=RunInstances&&ImageId=ami-b770fbd8';
function getSignatureKey(key, date, region, service){
var newKey = "AWS4" + key;
var kDate = new Hashes.SHA256().b64_hmac(newKey, date);
var kRegion = new Hashes.SHA256().b64_hmac(kDate, region);
var kService = new Hashes.SHA256().b64_hmac(kRegion, service);
var kSigning = new Hashes.SHA256().b64_hmac(kService, "aws4_request");
return kSigning;
}
var gdt = new GlideDateTime();
var datestamp = gdt.getDate().getByFormat('yyyyMMdd') + 'T' +
gdt.getTime().getByFormat('HHmmss') + 'Z';
var amzdate = gdt.getDate().getByFormat('yyyyMMdd')+"";
var canonical_uri = '/';
var canonical_querystring = request_parameters;
var canonical_headers = 'host:' + host + '\n' + 'x-amz-date:' + amzdate + '\n'
var signed_headers = 'host;x-amz-date';
var payload_hash = new Hashes.SHA256().hex("");
var canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash;
var algorithm = 'AWS4-HMAC-SHA256';
var credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request';
var string_to_sign = algorithm + '\n' + amzdate + '\n' + credential_scope + '\n' + new Hashes.SHA256().hex(canonical_request);
var signing_key = getSignatureKey(secret_key, datestamp, region, service);
//Python
//var signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()
var signature = new Hashes.SHA256().hex_hmac(signing_key, string_to_sign);
var authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature
var headers = {'x-amz-date':amzdate, 'Authorization':authorization_header}
var request_url = endpoint + '?' + canonical_querystring
var httpRequest = new GlideHTTPRequest(request_url);
httpRequest.setRequestHeader(headers);
var res = httpRequest.get();
gs.print(res.statusCode);
gs.print(res.allHeaders);
gs.print(res.body);
Check the URL construction. For one, the request_parameters have some missing and misplaced delimiters.
var request_parameters = 'AWSAccessKeyId=' + access_key +
'&Action=RunInstances&ImageId=ami-b770fbd8';
In addition to inspecting and testing the resulting URL, you might also try to simply the syntax to make it easier to check and update. Just as an example, the following
var credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request';
var string_to_sign = algorithm + '\n' + amzdate + '\n' + credential_scope + '\n' + new Hashes.SHA256().hex(canonical_request);
could be written as follows (which seems easier to check to me):
var credential_scope = [
datestamp,
region,
service,
'aws4_request'
].join('/');
var string_to_sign = [
algorithm,
amzdate,
credential_scope,
new Hashes.SHA256().hex(canonical_request)
].join('\n');

how to add substring into a string

I have a url and i need to enter a port number to the url.
the url is not a valid url.
here is few show cases :
https://example.com_users/param/param/param - https://example.com_users:8080/param/param/param
http://example.co_setting/param/param/param - http://example.co_settings:1000/param/param/param
http://example.co_setting- http://example.co_settings:1000
const addPort = (url,port) =>{
combined = ???????? // how to combian them
return combined
}
You could use a regular expression:
const addPort = (url, port) =>
url.replace(/^(https?:\/\/)?([^/]*)(\/.*)?$/, '$1' + '$2:' + port + '$3');
console.log(addPort('http://www.example.com/full/url/with/param', '8080'))
var urlstring = 'https://example.com_users/param/param/param';
var port = ':8080';
var allparts = urlstring.split('//');
var last = allparts[1];
var alllastparts = last.split('/');;
alllastparts[0] = alllastparts[0]+port;
alert(allparts[0]+ '//' + alllastparts.join('/'));
console.log(allparts[0]+ '//' + alllastparts.join('/'));

Categories

Resources