Javascript to open file and read something using regular expressions - javascript

I would like to make a small gadget to use at work and show me the time of check in, from the morning.
I am trying to open a network file using http protocol and read from it the line which is referring to my check in.
This is located on our intranet and can be accessed like this:
filename = 'http://www.intranet.loc/docs/dru/Acces/' + ystr + '-' + mstr + '-' + dstr + '.mvm';
Every employer has a unique code for check in. The structure of the check In file is like this:
12:475663:1306285:072819:11:1:1:0:
12:512362:1306285:072837:11:1:1:0:
12:392058:1306285:072927:11:1:1:0:
12:516990:1306285:072947:11:1:1:0:
12:288789:1306285:073018:11:1:1:0:
12:510353:1306285:073032:11:1:1:0:
12:453338:1306285:073033:11:1:1:0:
12:510364:1306285:073153:11:1:1:0:
12:510640:1306285:073156:11:1:1:0:
In this example, 12 is the gate number, which I don't need, the second is my ID, the third is the current date, and what I need is the fourth (the hour).
Edit:
I am using this function to return the content of the mvm file with no luck:
function readfile(fileToRead) {
var allText = [];
var allTextLines = [];
var Lines = [];
var Cells = [];
var txtFile = new XMLHttpRequest();
txtFile.open("GET",fileToRead, true);
allText = txtFile.responseText;
allTextLines = allText.split(/r\r\n|\n/);
return allTextLines;
}

Do you really need a RegEx? Would it be possible to split the line by ":"?
$.get('http://www.intranet.loc/docs/dru/Acces/' + ystr + '-' + mstr + '-' + dstr + '.mvm', function(data) {
var lines = data.split("\n"),
values;
for (var i in lines) {
values = lines[i].split(':');
}
});
With this you would have everything you need.

Related

Filename issue in Photoshop script that put multiple PNGs on mockups

I am using JS with Photoshop to put multiple PNGs on the mockup and export them as JPGs. Everything is working fine except for the exported file name. It names the file with the current date and time.
var filename = docPath + '/' + basename + "#" + getTime() + '.jpg';
I want it to name the files in a sequence like, Mockup 1, Mockup 2, Mockup 3 ...
Is there any way to do it?
Any help will be highly appreciated.
Example to gain correct Filename:
docPath = "/myProjectFolder/img"; //set the path / maindirectory you need
basename = "myFileprimaryName"; // set the primary Name you want to use
//getDate ist a function of the Date object - you need to instance it to call
var myDate = new Date();
var filename = docPath + '/' + basename + "#" + myDate.getTime() + '.jpg';
//Following Lines will just give you an output, to check if variables
//are set correct - you will not need them in final code
const data = {
message: filename,
}
$('#msg').html(data.message)
Note: Not sure if '#' is really the best sign to use to set in Filenames, I would rather preferre to use "_" instead, due to interoperability on different filesystems.
To save the file you will need to create a new File-Object, assign the Filename to it and save the file through the .saveAs() function, like in the following.
Example to save File:
var newFile = new File(filename);
var saveOptions = new JPEGSaveOptions();
saveOptions.embedColorProfile = true;
saveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
saveOptions.matte = MatteType.NONE;
saveOptions.quality = quality;
document.saveAs(newFile, saveOptions, true, Extension.LOWERCASE);
Now if you want to generate and save multiple files, it's pretty basic for you just jave to combine the two snipplets in a for-Loop.
Example to generate multiple files / filenames - out of one source file:
docPath = "/myProjectFolder/img";
basename = "myFileprimaryName";
var filename;
var saveOptions = new JPEGSaveOptions();
saveOptions.embedColorProfile = true;
saveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
saveOptions.matte = MatteType.NONE;
saveOptions.quality = quality;
var myDate = new Date();
var i;
for (i = 0; i < cars.length; i++) {
filename = docPath + '/' + basename + +"#" + i + myDate.getTime() +'.jpg';
var newFile = new File(filename);
document.saveAs(newFile, saveOptions, true, Extension.LOWERCASE);
}
Note: this will create the same file with the same content multiple times (e.g. if you are a teacher who wants to handle working copies of the same file to multiple students. If you instead want to save different files, I would rather do the following: Check the Maximum Count of Basename#Count of existing files in directory, increment it and save lateron new file with incremented Count.

Local Storage Not Working As Expected

I built an app that I then built with PhoneGap Build.THe purpose is for it to run a code (starts at var Quotes once per day when the app is loaded).
When debugging why it wasn't working I noticed that in console I was getting back my message "Local storage didn't work". This means that my initial localstorage.getItem which is supposed to make sure the local storage can be read is returning null. So my code never gets executed.
What am I doing wrong?
function onDeviceReady() { //Do something when the app on device is loaded
var localVal = localStorage.getItem('DateOpened');
if(localVal == null){
console.log("LocalStorage did not work...")}
else
{
var tempd = new Date(); //Get today's date
var str = tempd.getDay() + tempd.getMonth() + tempd.getFullYear();
if(localVal.localeCompare(str) == -1)
{
var Quotes = [];
var ID = [];
var Tag = [];
var seen = [];
localStorage.setItem('DateOpened',str);
console.log("The App Ran, you can get a new fat tomorrow");
console.log("Todays date:" + str);
}
}
}
Initially, there will be no DateOpened item in local storage, so your code will follow the "did not work" branch, because getItem returns null for things that don't exist. That branch never sets anything in DateOpened, so...you'll always follow that branch.
The fix is not to skip over your code setting DateOpened if the device has local storage.
There's also an unrelated problem: Your var str = tempd.getDay() + tempd.getMonth() + tempd.getFullYear() does not produce a string, it produces a number formed by adding those values together, since they're all numbers. Your later localeCompare will fail because it's not a string. You also have the fields in the wrong order for a meaningful textual comparison — you need year first, then month, then day.
Here's a minimal fix, see comments:
function onDeviceReady() {
var tempd = new Date();
// Note that by adding strings in there, we end up with a string instead of adding.
// Note the order: Year first, then month, then day.
// Also, since we display it, we put separators in and add 1 to month (since Jan = 0).
var str = tempd.getFullYear() + "-" + (tempd.getMonth() + 1) + "-" + tempd.getDay();
var localVal = localStorage.getItem('DateOpened');
// If we have no stored value, or it's more than a day old by your definition,
// do your stuff and store the new date
if (localVal == null || localVal.localeCompare(str) < 0) {
var Quotes = [];
var ID = [];
var Tag = [];
var seen = [];
localStorage.setItem('DateOpened', str);
console.log("The App Ran, you can get a new fat tomorrow");
console.log("Todays date:" + str);
}
}
I think this is help full for you.
function onDeviceReady() { //Do something when the app on device is loaded
var localVal = localStorage.getItem('DateOpened');
if (typeof(DateOpened) == "undefined")
console.log("LocalStorage did not work...")}
else
{
var tempd = new Date(); //Get today's date
var str = tempd.getDay() + tempd.getMonth() + tempd.getFullYear();
var allRecords=JSON.parse(localStorage.getItem("DateOpened"));
if(allRecords == -1)
{
var Quotes = [];
var ID = [];
var Tag = [];
var seen = [];
localStorage.setItem('DateOpened',str);
console.log("The App Ran, you can get a new fat tomorrow");
console.log("Todays date:" + str);
}
}
}

Javascript Web API JSON Parsing Format issue

Hi i have an issue with a few lines of code in JS and formatting my JSON data. Basically in my DB i have a field that is set to nchar(10) but some of the data in the fields are for example only 8 characters long.
The problem i have is when my JS generates a link from JSON data it attaches Spaces to the Data to compensate the (10) characters. For example clicking a link generated from the JS Would generate a link for me like this http://....api/Repo/rep10016
In my JSON it passes in this data
rep10016
But my JS is grabbing this data for the link adding spaces up to 10 as it is a nchar(10) like this.
repoCode = "rep10016 "
But i only want
repoCode = "rep10016"
My JS Code
function displayRepos(repo) {
var table = document.getElementByrCode("rList");
table.innerHTML = "";
for (var i = 0; i < arr.length; i++)
{
var rCode = arr[i].repoCode;
cell2.innerHTML = "<a href='#'rCode='" + rCode + "' " + " >Repo List</a>";
document.getElementByrCode(rCode).onclick = getRepo;
}
function getRepo(rep)
{
var repoUrl = genUrl+rep.target.rCode+"?code="+rep.target.rCode;
......
}
The repoUrl variable is generating a link like this
"http://....api/Repo/rep10016 ?code=rep10016 /"
How can i get my code to only take the actual data and not format it to the nchar(10) format that is in my db??
repoCode.trim() will do the trick.
I would use string.trim();
var orig = 'foo ';
console.log(orig.trim()); // 'foo'

Javascript eval

I am trying to get the following working. It seemed to work initially, but somehow it stopped working
var setCommonAttr = "1_row1_common";
var val = document.getElementById("abc_" + eval("setCommonAttr")).value;
what is wrong with above?
The above code is little different from what I am trying to accomplish. I gave the above example just not to make things complicated here. Below is what I am trying to accomplish:
First I am getting an existing element as follows. The element is a
<tr id="row_1_4_2009_abc" class="rowclick">
<td></td>
</tr>
I am using jquery to get the id on click of a row:
$(".rowclick").click(function() {
var row_id = $(this).attr("id");
var getAttributes = row_id.split("_");
var setCommonAttr = getAttributes[1] + "_" + getAttributes[2] + "_" + getAttributes[3] + "_" + getAttributes[4];
var new_row_id = document.getElementById("new_row_" + setCommonAttr).value;
});
You shouldn't need eval() to do this. The value you want is already a variable in JavaScript. Try:
var setCommonAttr = "1_row1_common";
var val = document.getElementById("abc_" + setCommonAttr).value;
Will everything be in that form? row_xxx_xxx_xxx_xxx
if so, why not var new_row_id = document.getElementById("new_" + row_id).value;
You don't need to call eval().
You can just concatenate the string with the variable:
var setCommonAttr = "1_row1_common"; var val = document.getElementById("abc_" + setCommonAttr).value;

Represent a query string in JSON

I have this Javascript data:
[{id:123,type:"test"},{id:154,type:"another"}]
How would you transform that into something so that I can pass it as a HTTP post request?
menu[0][id] = 123
menu[0][type] = test
menu[1][id] = 154
menu[1][type] = another
I dont want to pass the actual JSON data, I want to clean it up and pass it as formatted HTTP paramaters.
EDIT
Was able to parse the object on the client side using something like this, maybe you guys would suggest something better before I sign this as "answered"?
this.serialize = function(elem) {
var childs = elem.childElements();
var str = "";
for(var i=0, item; i<childs.length; i++) {
item = childs[i];
str += ((i)?"&":"")+"menu[" + i +"][id]=" + item.id.replace(/item_/,"");
str += "&menu[" + i +"][type]=" + item.className;
str += "&menu[" + i +"][section]=" + elem.id;
str += "&menu[" + i +"][position]=" + i;
}
return str;
}
var data = [{id:123,type:"test"},{id:154,type:"another"}];
var params = new Array();
for(var x = 0; x < data.length; x++) {
params.push("id=[" + x + "]=" + escape(data[x].id));
params.push("type=[" + x + "]=" + escape(data[x].type));
}
alert(params.join("&")); // output: id=[0]=123&type=[0]=test&id=[1]=154&type=[1]=another
Is that what you want?
menu0.id=123&menu0.type=test&menu1.id=154&menu1.type=another
This is fairly easy to parse on the server, in that it's a regular format.
I believe HTTP POST only accepts a flat key/value collection, not any arbitrary JavaScript data structure.
If you can flatten it (for example, like John Stauffer shows), and if you're posting to your own domain, you can use an XMLHttpRequest to post and pass the key/value collection, formatted like a query string, with the .send(data) method.
If you don't want to implement it yourself most JavaScript libraries should have an implementation (e.g. jQuery.post).
"?qsparam=" + escape("[{id:123,type:'test'},{id:154,type:'another'},...]")

Categories

Resources