JavaScript file scanning: get int at certain line - javascript

I have a file that looks like this on my server:
0 2
1 8
2 3
3 1
//...
I already know how to get the contents of the file, I do it like this:
var file = 'fileName';
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
}
}
}
rawFile.send(null);
The integer on the left in the file increments for each entry, the integer on the right is random. My program specifies an int n and I want to retrieve the value to the right of the left-hand value that is equal to n. In the example, if program specifies n = 2, I want to get 3. How do I do this?

The more traditional approach of searching line by line
var n = '2', l;
var file = 'fileName';
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText,
lines = allText.split("\n"),
line;
for (var i=0; i<lines.length; i++) {
if (lines[i].indexOf(n) === 0) {
line = lines[i];
break;
}
}
var numbs = line.split(/\s+/);
l = numbs[1];
}
}
}
rawFile.send(null);

One way would be:
var n = 2;
var right = allText.match(new RegExp('^' + n + ' (\\d+)$', 'm'))[1];

Related

How to assign the value of toggle button (ngx-toggle) in angular page according to the output of a bash script?

I have an Angular page, where I have a few toggle buttons. The state of those, I have to determine based on the output of a bash script. I'm using ngx-toggle. Now, these toggle button shows if JMS adapters are running on different servers. And I have to take that status from the server.
<ngx-toggle id="devBase" [value]=""></ngx-toggle>
Till now, I've tried to read the status from a text file, but I'm unable to update the value of toggle buttons.
readTextFile(file) {
let rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
let allText = rawFile.responseText;
let lines = allText.split("\n");
let devBase: boolean;
for (let line = 0; line < lines.length; line++) {
if (lines[line].trim() == "devBase=1") {
console.log(devBase);
devBase = true;
}
if (lines[line].trim() == "devBase=0") {
console.log(devBase);
devBase = false;
}
}
}
}
}
rawFile.send(null);
}
When I'm using [(value)]="devBase", it is unable to process.
Two way binding is working. So the html code will be
<ngx-toggle id="devBase" [(value)]="devBase"></ngx-toggle>
The reason it was not working earlier is that the devBase was defined inside a function in my ts file. I returned this value from the function and take it in a universal variable.
readTextFile(file) {
let rawFile = new XMLHttpRequest();
let lines;
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
let allText = rawFile.responseText;
lines = allText.split("\n");
}
}
}
rawFile.send(null);
return lines;
}
And in the outside of this function,
lines: string[];
this.lines = this.readTextFile("http://orapoc06:8087/JavaBridgeTemplate621/dist/assets/files/status.txt");

Function won't return a value [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I'm making a password generator. Trying to implement pass-phrases.
The function loadFile(); won't return a value to my main function, generate();
I think I'm too close to the problem and can't logic it out. I could use some help. Thank you.
Test site: https://jf0.000webhostapp.com/passWordGenerator/
test.js source: https://jf0.000webhostapp.com/passWordGenerator/test.js
The source is getting kind of long, sorry.
//Main generate password function
function generatePassword(){
var x = document.getElementById("passOutput");
var p = document.getElementById("testP");
x.value = generate();
//Make sure they aren't using an insecure number of characters
checkMaxChars();
p.innerText = x.value;
}
//Generate a password. 3 passSets for customization, one for passphrase
function generate(){
var nL = document.getElementById("noLetters");
var nN = document.getElementById("noNumbers");
var nS = document.getElementById("noSymbols");
var pPK = document.getElementById("passWordPhrase");
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var numbers = "0123456789";
var symbols = "!##$%^&*()_+~`|}{[]:;?,.-='";
var maxChars = document.getElementById("maxCharControl").value;
var generatedPass = "";
var holdPass = "";
//Main loop
for(var i = 0;i < maxChars;i++){
//Pick random value for each passSet
var passSet1 = chars.charAt(Math.random() * chars.length);
var passSet2 = numbers.charAt(Math.random() * numbers.length);
var passSet3 = symbols.charAt(Math.random() * symbols.length);
//if a checkbox is selected, clear out that value
if(nL.checked == true){passSet1 = "";}
if(nN.checked == true){passSet2 = "";}
if(nS.checked == true){passSet3 = "";}
//Randomly select a set to be added to holdPass, or not if it is empty.
var r = Math.floor((Math.random() * 4) + 1);
if(r == 1){if (passSet1 == ""){i--}else{holdPass += passSet1;}}
if(r == 2){if (passSet2 == ""){i--}else{holdPass += passSet2;}}
if(r == 3){if (passSet3 == ""){i--}else{holdPass += passSet3;}}
if(r == 4){
if(pPK.checked == true){
//get the value from loadFile(); and apply it to passSet4, add that to holdPass.
}}
}
generatedPass = holdPass;
console.log("Max Characters:" + maxChars);
console.log("passSet1:" + passSet1);
console.log("passSet2:" + passSet2);
console.log("passSet3:" + passSet3);
console.log("Iteration:" + i);
console.log("Random Position:" + r);
console.log("Password:" + holdPass + "::::" + holdPass.length);
//return password
return generatedPass;
}
//Make sure they didn't select all the checkboxes
function checkBoxes(){
var nL = document.getElementById("noLetters");
var nN = document.getElementById("noNumbers");
var nS = document.getElementById("noSymbols");
var pP = document.getElementById("passWordPhrase");
var nA = document.getElementById("noticeArea");
var nT = document.getElementById("noticeAreaText");
if(nL.checked == true && nN.checked == true && nS.checked == true){
nL.checked = false;
nN.checked = false;
nS.checked = false;
nA.style.display = "block";
nT.innerHTML = "You cannot select all checkboxes at once.";
window.setTimeout(hideNotice,5000);
}
else{
nA.style.display = "none";
nT.innerHTML = "";
}
}
//make sure the max characters is greater than 8
function checkMaxChars(){
var maxChars = document.getElementById("maxCharControl").value;
var nA = document.getElementById("noticeArea");
var nT = document.getElementById("noticeAreaText");
var x = document.getElementById("passOutput");
console.log(maxChars);
if (maxChars < 8){
x.value = "";
nA.style.display = "block";
nT.innerHTML = "You cannot generate a password less than 8 characters in length for security reasons.";
window.setTimeout(hideNotice,7000);
}
}
//hides the notice area div once the message is completed
function hideNotice(){
var nA = document.getElementById("noticeArea");
var nT = document.getElementById("noticeAreaText");
nA.style.display = "none";
nT.innerHTML = "";
}
//Load file
function loadFile() {
var xhttp = new XMLHttpRequest();
var x;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
x = this.responseText;
parseResponse(x);
}
}
xhttp.open("GET", "wordList.csv", true);
xhttp.send();
return x;
}
//Format response
function parseResponse(x){
console.log("MADE IT HERE!");
var dS,sV1,rPos;
dS = x.split(",");
for(var i =0;i < dS.length;i++){
sV1 = dS[i];
}
x = sV1;
}
The results of an AJAX request will never be available until after the function that initiated it completes. You are attempting to return x before at the end of the function that initiates the request, which is before the AJAX request has finished.
You need to move that line into your AJAX success handler.
function loadFile() {
var xhttp = new XMLHttpRequest();
var x;
// The onreadystatechange callback function will execute
// at some future point after loadFile has completed, so
// you can only gain access to the AJAX result from within
// that function.
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
x = this.responseText;
parseResponse(x);
return x;
}
}
xhttp.open("GET", "wordList.csv", true);
xhttp.send();
}
Your xhttp request is opened asynchronously with the true in xhttp.open("GET", "wordList.csv", true); so x is returned before a value is assigned to it.
Edit: said synchronously instead of asynchronously because I am dumb

How can i read txt file line by line

I want to read txt file line by line, right now it's showing
everything that i have in my file, i want to pass each new line to variable ,how can i do it?
var file = "file:///C:/Users/Viktor/Desktop/test.txt";
function readTextFile(file,line) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function () {
if(rawFile.readyState === 4) {
if(rawFile.status === 200 || rawFile.status === 0) {
var allText = rawFile.responseText;
}
}
};
rawFile.send(null);
}
readTextFile(file);
You can split the string on the new lines.
var allText = rawFile.responseText,
lines = allText.split(/\n/g); //.split("\n")
console.log(lines.length);

javascript - cannot retrieve array data

I am trying to write a OBJMesh model reader and I've got the OBJMesh class setted up, but when I try to retrieve the stored data in the array by creating the OBJMesh object and call the get function, it doesn't do it.
Here's the code
OBJMesh.js
function OBJMesh(file)
{
this.modelVertex = [];
this.modelColor = [];
this.init = false;
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
var objmesh = this;
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState == 4)
{
if(rawFile.status === 200 || rawFile.status === 0)
{
var allText = rawFile.responseText;
var lines = allText.split("\n");
for(var i = 0; i < lines.length; i ++)
{
var lineData = lines[i];
var lineString = lineData.split(" ");
if(lineString[0] === "v")
{
var x = parseFloat(lineString[1]);
var y = parseFloat(lineString[2]);
var z = parseFloat(lineString[3]);
objmesh.modelVertex.push(x);
objmesh.modelVertex.push(y);
objmesh.modelVertex.push(z);
objmesh.modelColor.push(0.0);
objmesh.modelColor.push(0.0);
objmesh.modelColor.push(0.0);
objmesh.modelColor.push(1.0);
//document.getElementById("textSection").innerHTML = objmesh.modelVertex[0];
}
}
}
}
objmesh.init = true;
}
rawFile.send();
}
OBJMesh.prototype.getModelVertex = function ()
{
return this.modelVertex;
};
OBJMesh.prototype.getModelColor = function ()
{
return this.modelColor;
};
OBJMesh.prototype.getInit = function ()
{
return this.init;
};
main.js
var cubeModel;
function main()
{
cubeModel = new OBJMesh("file:///Users/DannyChen/Desktop/3DHTMLGame/cube.obj");
while(cubeModel.getInit() === false)
{
//wait for it
}
var cubeVertex = cubeModel.getModelVertex();
document.getElementById("textSection").innerHTML = cubeVertex[0];
}
it just keeps printing out "undefined". Why's that? and how can I fix it??
but it seems that onreadystatechange is an async-Call so,
this.init = true;
will be set before the function onreadystatechange is called.
May be you could set at the end of the onreadystatechange function
objmesh.init = true;
i hope this helps

Add data to local array in javascript

I've been trying to add data into my array for sometime now and it doesn't work. I have the following code:
function OBJMesh(file)
{
this.modelVertex = [];
this.modelColor = [];
var that = this;
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState == 4)
{
if(rawFile.status === 200 || rawFile.status === 0)
{
var allText = rawFile.responseText;
var lines = allText.split("\n");
for(var i = 0; i < lines.length; i ++)
{
var lineData = lines[i];
var lineString = lineData.split(" ");
if(lineString[0] === "v")
{
var x = parseFloat(lineString[1]);
var y = parseFloat(lineString[2]);
var z = parseFloat(lineString[3]);
/*
this.modelVertex.push(x);
this.modelVertex.push(y);
this.modelVertex.push(z);
this.modelColor.push(0.0);
this.modelColor.push(0.0);
this.modelColor.push(0.0);
this.modelColor.push(1.0);
*/
that.modelVertex.push(10.0);
//document.getElementById("textSection").innerHTML = "testing";
}
}
}
}
}
rawFile.send();
}
OBJMesh.prototype.getModelVertex = function ()
{
return this.modelVertex;
};
OBJMesh.prototype.getModelColor = function ()
{
return this.modelColor;
};
If I comment out the this.modelVertex.push(10.0); it gets pass the error and prints out "testing". But if I uncomment it, it gets stuck there and won't print anything out. Why is it doing this? how can I solve it so it actually pushes the given data to the this.modelVertex array?
Many Thanks
Edit: I have edited my code after dystroy told me what to do and it do work when I try to print the values in the OBJMesh constructor (shown above), but when I try to do this by creating the object in my main function (shown below) it doesn't print anything.
var cubeModel;
function main()
{
cubeModel = new OBJMesh("file:///Users/Danny/Desktop/3DHTMLGame%202/cube.obj");
document.getElementById("textSection").innerHTML = cubeModel.getModelVertex();
}
this isn't your new instance of OBJMesh in the callback but the XMLHttpRequest.
Start by referencing the desired object just before defining the callback :
var that = this;
rawFile.onreadystatechange = function ()
then use it :
that.modelVertex.push(10.0);
Answer to the question in your edit :
Your constructor contains an asynchronous request. Which means your array isn't available immediately but later.
A solution would be to pass a callback to the constructor :
function OBJMesh(file, doAfterInit) {
this.modelVertex = [];
this.modelColor = [];
var that = this;
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function () {
if(rawFile.readyState == 4)
{
if(rawFile.status === 200 || rawFile.status === 0)
{
var allText = rawFile.responseText;
var lines = allText.split("\n");
for(var i = 0; i < lines.length; i ++)
{
var lineData = lines[i];
var lineString = lineData.split(" ");
if(lineString[0] === "v"){
that.modelVertex.push(10.0);
if (doAfterInit) doAfterInit();
}
}
}
}
}
rawFile.send();
}
...
cubeModel = new OBJMesh("file:///Users/Danny/Desktop/3DHTMLGame%202/cube.obj", function() {
document.getElementById("textSection").innerHTML = cubeModel.getModelVertex();
});
But having a class here doesn't look like a smart idea.

Categories

Resources