Get undefined callback - javascript

I have code like this when I console log the fileContent is gives correct output but when I try to get it as a return it gives error.
I want to use the contents of csv file in other functions.While keeping code clean.
;(function(){
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
var fileContent;
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
fileContent =csvJSON(allText);
return fileContent;
}
}
}
rawFile.send(null);
}
function csvJSON(csv){
var lines=csv.split("\n");
var result = [];
var headers=lines[0].split(",");
for(var i=1;i<lines.length;i++){
var obj = {};
var currentline=lines[i].split(",");
for(var j=0;j<headers.length;j++){
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
return result; //JavaScript object
//return JSON.stringify(result); //JSON
}
var mainContent = readTextFile("main.csv");
})();

You should know a little about asynchronous work. When you set handler to readystatechange you just subscribing to that event from XMLHttpRequest, your function will be called when this event is fire. Therefore this function can not return something back to you. Except if you specify another function called callback and in handler after all call it.
Look at this:
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
var fileContent;
rawFile.onreadystatechange = function () {
if(rawFile.readyState === 4) {
if(rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
fileContent =csvJSON(allText);
callback(fileContent);
}
}
}
And when you want request:
readTextFile('main.csv', function(data) {
console.log(data);
}
This is how asynchronous calculation work.

Related

readTextFile function returns undefined. Why?

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
function 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;
console.log(allText);
}
}
}
rawFile.send(null);
}
readTextFile("/input.txt");
I want to read a txt file and print it to console but I'm getting undefined. What is the reason for that?
const fs = require('fs');
let text = fs.readFileSync('./input.txt');
text = text.toString();
console.log(text);
Use toString() method returns the buffer object.

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);

How to return "finished" section of a javascript code

I want to upload an image file to server and then show it on browser editor on return.
For that, I have #fileInput form input (type file) to upload an image to server.
On change #fileInput, I trigger uploadAndReadURLfunction which calls app.uploader for upload.
When upload is finished, it returns to line commented "Coming here" below. However, I want it to return to the line commented "Not coming here". How can I make this happen.
var app = app || {};
(function(o) {
"use strict";
var ajax, getFormData;
ajax = function(data) {
var xmlhttp = new XMLHttpRequest(), uploaded;
xmlhttp.addEventListener('readystatechange', function() {
if(this.readyState === 4) {
if(this.status === 200) {
var res =this.response;
if(res == 1) {
console.log(res); // Coming here.
}
}
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function(source) {
var data = new FormData(), i;
for(i = 0; i < source.files.files.length; i = i + 1) {
data.append('file[]', source.files.files[i]);
}
data.append('ajax', true);
return data;
};
o.uploader = function(options) {
o.options = options;
if(o.options.files !== undefined) {
ajax(getFormData(o.options));
}
}
}(app));
function uploadAndReadURL(input) {
if(input.files && input.files[0]) {
var f = document.getElementById('fileInput');
app.uploader({
files: f,
processor: "/geornal/image",
finished: function(data) {
console.log("burada2."); // Not coming here..
},
error: function() {
console.log('Not working');
}
});
}
}
$(document).ready(function(){
$("#icerik2").on("change", "#fileInput", function(){
uploadAndReadURL(this);
});
});
There is "finished:" section in uploadAndReadURL function. I don't
know how to call "finished" from app function.
Try calling o.options.finished() at if statement within readystatechange handler
if(res == 1) { o.options.finished(res); }

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