Writing onto HTML page - javascript

So for a brief context, my program reads in a file and displays it onto the html page. The code below uses a regex expression to read that file and extract the errors. Instead of using console.log each time and debugging, is there any I way I could just write the results onto the HTML page?
When I used:
document.getElementById("").innerHTML
it would just print out the last summary instead of printing out all of the summaries.
I tried using a controller and ng-repeat (AngularJS) to do it, but somehow I did not do it right.
Any ideas -- doesn't have to be in AngularJS???
while ((match = reDiaBtoa.exec(reader.result)) != null) {
if (match.index === reDiaBtoa.lastIndex) {
reDiaBtoa.lastIndex++;
}
// View your result using the match-variable.
// eg match[0] etc.
// extracts the status code: ERROR
if (match[2] === "ERROR" || match[2] === "FATAL" || match[2] === "SEVERE") {
console.log("Time: " + match[1]);
console.log("Thread Name: " + match[3]);
console.log("Source name & line number: " + match[4]);
console.log("Log Message: " + match[5] + '\n');
console.log("-----------------------------------------------------------------");
}
} //end of the while loop ((match = reDiaBtoa.exec.....))

If you use
document.getElementById("someId").innerHTML =
it'll overwrite the existing html.
instead, use
document.getElementById("someId").innerHTML +=

Create a string variable before your while loop and then append to it in your loop:
var outputToDisplay = "";
//While loop
outputToDisplay += "Time: " + match[1];
//etc
//End While
document.getElementById(theId).innherHTML = outputToDisplay;

Related

Fast-CSV modify before loading CSV to MySQL

I am trying to load a CSV file to my MYSQL database, however before I do so I need to modify it slightly. The CSV file is Pipe delimitated (|)
I have a column in the CSV file called Party:Identification. This column has results such as "a:hello, b:hi c:151 ......" This can go on infinitely.
I only need to get the value for c. I have come up with a method that works for this, however I am stuck on how to modify the value before the file is inserted into the database.
I tried replacing all the ":" in the headers with "" and then using .transform to modify the values, however this doesn't appear to change the values in the column, only the header. Code is attached below.
csv.parseFile(req.file.path, {
headers: headers => headers.map(function (header) {
const newHeaders = header.replaceAll(" ", "").replaceAll(":", "")
console.log(newHeaders)
return newHeaders
}),
delimiter: '|'
})
.transform(function(data) {
console.log(data)
PartyIdentification: getPartyID(data.partyIdentification)
})
.on("error", (err) => console.error(err))
.on("finish", function () {
query("LOAD DATA LOCAL INFILE '" +
file +
"' INTO TABLE table " +
" FIELDS TERMINATED BY '|'" +
" LINES TERMINATED BY '\n'" +
" IGNORE 1 ROWS;").then(r =>
console.log(file)
)
})
function getPartyID(str) {
if (str === undefined) return ""
const split = str.split(",")
const value = split.find(val => {
return val.includes("c")
})
if(value === undefined) return ""
return (value.split(":")[1].trim())
}
You can use a regex to parse the value of c:123 in a string:
function getPartyID(str) {
if (str === undefined) return "";
const m = str.match(/\bc:([^ ]*)/);
return m ? m[1] : null;
}
[
"a:hello, b:hi c:151 d:foo",
"a:hello, b:no_c",
].forEach(str => {
console.log(str, '==>', getPartyID(str));
});
Output:
a:hello, b:hi c:151 d:foo ==> 151
a:hello, b:no_c ==> null
Explanation of regex:
\b -- word boundary
c: -- literal text
([^ ]*) -- capture group 1 with value, up to and excluding space
UPDATE 1: Based on additional question on how to insert modified data into MySQL, here is a solution that does not use INFILE, but instead loads the file into memory (here simulated with const input), modifies the data as needed, and constructs a SQL statement that inserts all the data. IMPORTANT: You likely want to add escapes against SQL injections.
const input = `Name|Party:Identification|Date
Foo|a:hello, b:hi c:151 d:foo|2022-01-11
Bar|a:hola, b:hey c:99 d:bar|2022-01-12
Nix|a:nix, b:ni d:nix|2022-01-13`;
const partIdFieldName = 'Party:Identification';
function getPartyID(str) {
if (str === undefined) return "";
const m = str.match(/\bc:([^ ]*)/);
return m ? m[1] : 0;
}
let partIdIdx = 0;
let data = input.split(/[\r\n]+/).map((row, idx) => {
let cells = row.split('|');
if(idx === 0) {
partIdIdx = cells.indexOf(partIdFieldName);
} else {
cells[partIdIdx] = getPartyID(cells[partIdIdx]);
}
return cells;
});
//console.log('data', '==>', data);
let sql = 'INSERT INTO tbl_name\n' +
' (' + data[0].map(val => '"' + val + '"').join(',') + ')\n' +
'VALUES\n' +
data.slice(1).map(row => {
return ' (' + row.map(val => /^[\d+\.]+$/.test(val)
? val
: '"' + val + '"'
).join(',') + ')'
}).join('\n') + ';';
console.log(sql);
Output:
INSERT INTO tbl_name
("Name","Party:Identification","Date")
VALUES
("Foo",151,"2022-01-11")
("Bar",99,"2022-01-12")
("Nix",0,"2022-01-13");
Don't bother fixing the csv file before loading, simply toss the unwanted columns as you LOAD it.
This, for example, will load only the 3rd column:
LOAD DATA ...
(#a, #b, c_col, #d, #e, ...)
That is, capture the unwanted columns into #variables that you will then ignore.
If you need to remove the c: before storing into the table, then
LOAD DATA ...
(#a, #b, #c, #d, #e, ...)
SET c_c0l = mid(#c, 3)
(or whatever expression will work. See also SUBSTRING_INDEX in case it would work better.)
LOAD DATA is plenty fast, even in this wasteful mode. And a lot less coding on your part.

Removing "," at the beginning of a line CSV

i want to convert a .csv file and write a new one. However I am not able to remove the first , i am kinda stuck here and it is driving me crazy.
This is my code:
var extractedtasks = tasks.slice(0, 3)
var extractedtasksformated = extractedtasks.toString().replace(/,$/g, "\n")
let csvformat = "EMAIL,PASSWORD,MAILBOX"
fs.writeFileSync(tasklocation[0], csvformat + "\n" + extractedtasksformated.replace(/,^/g,
""))
console.log(chalk.green("Successfully updated the CSV file"))
That's the output i am getting in the newly generated file
EMAIL,PASSWORD,MAILBOX
example1#gmail.com,Password123,example#gmail.com:password
,example2#gmail.com,Password123,example#gmail.com:password
,example3#gmail.com,Password123,example#gmail.com:password
Output extractedtasks:
[
'example1#gmail.com,Password123,example#gmail.com:password\r',
'example2#gmail.com,Password123,example#gmail.com:password\r',
'example3#gmail.com,Password123,example#gmail.com:password\r'
]
Output extractedtasksformated:
,example3#gmail.com,Password123,example#gmail.com:passwordxample#gmail.com:password
Because extractedtasks is an array, instead of converting it to a string you should just join it with the expected separator:
extractedtasks = [
'example1#gmail.com,Password123,example#gmail.com:password\r',
'example2#gmail.com,Password123,example#gmail.com:password\r',
'example3#gmail.com,Password123,example#gmail.com:password\r'
]
extractedtasksJoined = extractedtasks.join("\n")
// "example1#gmail.com,Password123,example#gmail.com:password\r\nexample2#gmail.com..."
// depending on the target line separator, you should also probably
// remove the "\r"
extractedtasksJoined = extractedtasksJoined.replace("\r", "")
// finally
fs.writeFileSync(tasklocation[0], csvformat + "\n" + extractedtasksJoined + "\n")

Checking for null only gets "Cannot read property '1' of null" in nodejs

I am trying to test for a null value after a # in a string. I have tried it various ways but I always get a Cannot read property '1' of null when submitting test data. I have ferreted out the errors I can think of but this one I cannot seem to get around. Please keep in mind I am a beginner at this, I haven't programmed since cobol days and the last time i worked on javascript was in the early 2000s.
//start test data, 5 possible strings that may pass through
elt.message = '#1a' //goes through the script good
elt.message = '#12b' // goes through
elt.message = '#123c' //goes through
elt.message = '' //is ignored
elt.message = '# ' //crashes server
//end test data
//First lets test to see if # is in the message. If true then we will parse it and add it to the database.
var str = elt.message;
var substr = '#';
var vtest = str.indexOf(substr) > -1;
if (vtest == 1){
var Vname = elt.author;
console.log('We tested for # and the value is true');
//extracts the number and the letter after the # from incoming chat messages
var test = elt.message; // replace with message text variable.
var pstr = test.match(/#(\d{1,3})([a-zA-Z])/);
if (pstr) {
var numbers = pstr[1];
var character = pstr[2];
var chupp = character.toUpperCase(); //Converts the lowercase to uppercase
}
//Tests to see if neither the question number or the possible answer is left out
//if (pstr[1] !== '' && pstr[2] !== ''){ //doesn't work =(
if (pstr[1] !== null && pstr[2] !== null){ //doesn't work either =(
console.log('we processed the numbers after the #sign and assigned the numbers and letter into variables.')
console.log('The question number is: ' + pstr[1]);
console.log('The letter processed is: ' + pstr[2]);
// Grabs the date and converts it into the YYYYMMDD string.
var dobj = new Date();
var dstr = dobj.toString();
var dsplit = dstr.split(' ');
let currentdate = `${dobj.getMonth() < '9' ? `0${dobj.getMonth() + 1}` :
dobj.getMonth() + 1}`;
currentdate = `${dsplit[3]}${currentdate}${dsplit[2]}`;
console.log(currentdate)//remove when done
//checks to see what the highest question number is in the database
var sel = con.query("SELECT * FROM questions WHERE ClassID = "+ currentdate + " ORDER BY QuesID DESC LIMIT 1", function (err, result){
if (err) throw err;
console.log('Total number of question records: '+result[0].QuesID);
console.log('the script is querying with' + pstr[1]);
console.log('the scripts answer letter is ' + pstr[2]);
if (pstr[2] != '' && pstr[1] <= result[0].QuesID ){
var query = con.query("SELECT * FROM questions WHERE ClassID = " + currentdate + " AND QuesID = " + pstr[1], function (err, result) { // Selects the record based on the Date and the question number variables provided above
if (err) throw err;
console.log('it got past the test')
if (result[0].AnsweredFirst === '' && result[0].AnswerLetter === chupp) { //Test to see if the AnsweredFirst is empty and that the Answer letter matchs with whats on file
console.log('MATCH!');//remove when done
var sql = "UPDATE questions SET AnsweredFirst = '"+ Vname + "' WHERE ClassID = " + currentdate + " AND QuesID = " + pstr[1]; //Updates the record with the first person who answered the question in the AnsweredFirst field
con.query(sql, function (err, result) {
if (err) throw err;
console.log(Vname + " answered question " + pstr[1] + " First!");
});
}
});
}
});
} else {
console.log('Either the question number or the letter was left blank so we are skipping'); //the viewer did not put in a proper number and letter after the # sign
}
} else {
console.log('No signs of # so skipping queries') //if there is no # sign the message is not processed
};
I added the rest of the script to get a better idea. Messages are passed to the server from a chat client.
I'll give it a try moving the block of code into the first if statement. I know its messy but honestly i am surprised I got this far.
var pstr = test.match(/#(\d{1,3})([a-zA-Z])/);
means that if no match is found for your regex, then pstr is null
in that case any index of pstr (like pstr[1], pstr[2]) will throw the error you described:
Cannot read property 'n' of null
Solution:
Before using indexes, check if the variable has a value or not
if(pstr !== null) {
// do something with pstr[1]
}
Edit:
And as nnnnnn rightly pointed out, you cannot explicitly store a null value in a string.
Look. If your test string did not match your regular expression then pstr assigned to null. Besides in next if condition you tried to check first element of pstr without checking it on null value:
if (pstr[1] !== null && pstr[2] !== null){ //doesnt work either =(
So, I think you need either add pstr!==null in second if or move all condition branch from this if inside then part of previous one if statement.

JavaScript recursion returns intermediate results rather than the final result

I have this JavaScript code where the rec() function is called by itself. The intent with this code is to loop through HTML-like text and replace all occurrences of the regex "IMG(.*)tid".
Once it has processed the string it should output the final version of the string in the "newText" variable (on line 5).
var text = '<IMG tid="302293901" title="test"><P></P><IMG tid="302293901" title="test">';
alert("source text: " + text);
var newText = rec(text);
alert("final source text: " + newText);
function rec(str) {
var i = str.search("IMG(.*)tid");
alert("value of i: " + i);
if (i > -1) {
str = str.replace("IMG", "BLA");
alert("modified source text: " + str);
rec(str);
}
return str;
}
When this code runs it does modify the source string in the "text" variable, replacing all occurrences of "IMG" with "BLA". During it's execution the function displays the expected final string that looks as shown below.
However the problem with this is that the alert box on line 5 does not return the results shown above, but an intermediary result (where only one of the "IMG" entries has been replaced).
The returned string is shown below.
So this code is probably incorrectly structured but in what way?
When you run rec again from within rec, you're not doing anything with the returned result. You need to change it to str = rec(str)
You need to return the value of rec...
function rec(str) {
var i = str.search("IMG(.*)tid");
alert("value of i: " + i);
if (i > -1) {
str = str.replace("IMG", "BLA");
alert("modified source text: " + str);
return rec(str);
}
return str;
}

Test if data from array has value Javascript

I want to test if the data array in the code below has content, because when a user gives a packageid (variable in the code below) that doesn't exist i want the else from the "if...else" to be executed. When i put in a packageid that exists everything works fine, but when i put in no number or a number that doesn't exist, the else side does't get evaluated.
function getInfoAndStatus(){
sym.$("customer_name").empty();
packageid = $("#tracknrfield").val();
var url = "http://student.howest.be/sylvain.vansteelandt/fedex/server/getPackageTracking.php?id=" + packageid;
$.getJSON(url,function(data){
if(data && data[0].id){
$("<span />", {
text: "Customer name: " + data[0].customer_name + " " + data[0].customer_firstname
}).appendTo(sym.$("customer_name"));
} else {
$("<span />", {
text: "The package with number " + packageid + " has not been found. Please try again."
}).appendTo(sym.$("customer_name"));
}
});
}
getInfoAndStatus();
Check your javacript console for any errors. data may be null or an empty array.
Adding a check for console.log(typeof data) may be useful as well.
Sight unseen, I'd most likely do something like if (data && data.length > 0)
If you check your console output, I'm betting you'll see an error there.
Your if check should look like:
if(data && data[0] && data[0].id)
As you may not have an element in your array.

Categories

Resources