Simply get each line in a .txt file into a javascript array - javascript

Thought this wouldn't be this difficult, but I'm simply trying to get the contents of a file and store each line into an array.
The 'file.txt' file (formatted as plain text):
file1.dwg
file2.dwg
file3.pdf
file4.dwg
file5.pdf
My javascript code:
function readTextFile('file.txt') {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", 'file.txt', false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
The syntax errors shown in the console:
- safari: SyntaxError: Unexpected string literal 'file.txt'. Expected a parameter pattern or a ')' in parameter list.
- chrome: Uncaught SyntaxError: Unexpected string
I'm running the files on a simple live server, with the following file structure:
- file.txt
- page.html
- script.js
The page.html just calls the script and is somewhere where I can work and open the console.
Why are the errors occurring, and how can they be fixed? I've tried to follow the instructions from this other post, but it has also failed: How to read a local text file?
Then I also tried the node solution and made my code like this:
var fs = require('fs');
var array = fs.readFileSync('file.txt').toString().split("\n");
for(i in array) {
console.log(array[i]);
}
I know nothing about Node but gave it a go - the errors were:
- chrome: Uncaught ReferenceError: require is not defined
- safari: ReferenceError: Can't find variable: require
Thanks for any help here - I don't know how to fix this seemingly simple problem.

function readTextFile(textFilePath) { //set a variable
var rawFile = new XMLHttpRequest();
rawFile.open("GET", textFilePath, false); //user variable here
let fileNameArray= [];//defined array here for now
rawFile.onreadystatechange = function (){
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
console.log(allText); //check in broswer console
//alert(allText)
//or enale the alert function
fileNameArray = allText.split('\n'); //split by line break and add to array
console.log(fileNameArray)
}
}
}
rawFile.send(null);
}
readTextFile('./text.txt'); // call function and pass relative path of text file here

Related

Getting the data from a .txt file into a .js file

We need to extract information from a .txt file, into a .js file.
We've tried using 'Fetch API' but without luck, is there any other way to go about this.
We are using a Node.js Server to see what's going on
This is the contents of the .txt file
2min = 2:00
2min away = 2:00
ScoreAway = 7
ScoreHome = 8
Time = 30:00
halvleg = 2nd
Serverside use Node Js and Clientside use fs.
In a browser you can use XMLHttpRequest. Like this:
function readTxtFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "neuro.txt", 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);
}
readTxtFile();

Javascript: parsed text in var into a set

I am trying to parse text from a dictionary.txt file for a web browser word game. I found How to read a local text file? and used the readTextFile(file) function the top commentor suggested. However, I don't understand how to get the parsed text into a set.
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText)
}
}
}
rawFile.send(null);
}
alert(allText) gives me a popup with words in the dictionary.txt, so I know the words are getting properly parsed into the variable allText.
How do I now move these words into a set structure for use in my game? I am thinking I would do this in my main program--run readTextFile, then move to set.
Also, as this is my first time using JavaScript, when I run readTextFile in my main program, do I need to do:
myWords = readTextFile("dictionary.txt");
To store allText intomyWords, or will simply doing:
readTextFile("dictionary.txt");
Make it so that I can access allText in my main program? I am unfamiliar with scoping in JS.
I think that all you will need to do is split the text file by new-lines and send the resulting list and instantiate a new Set object with the mentioned list.
Also, check out the documentation on MDN for the Set object.
let myWords = readTextFile("dictionary.txt");
console.log(myWords.has('apple')); // true
console.log(myWords.has('banana')); // true
console.log(myWords.has('carrot')); // true
console.log(myWords.has('durian')); // false
function readTextFile(filename) {
// Blah, blah, blah...
// Code to read the file and return a string...
// Ok, now we have a result:
let result =
`apple
banana
carrot
`;
return new Set(result.split('\n')); // Split the text by new-line and instantiate
}
We will need to know the format of the file to help you parse it. If it is a text file with a word on each line, then you could return allText; in your function, then put it into an array using
var myWords=readTextFile('dictionary.txt').split("\n");

Reading CSV file in to an array using javascript

I'm trying to do something fairly simple I think but I'm missing something. I've very new to Javascript. I'm trying to read a CSV file in to an array (in my code below I'm simply trying to output the data to an alert box). I keep getting an error "access denied."
function readTextFile(file) {
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;
alert(allText);
}
}
}
rawFile.send(null);
}
I suspect there is an issue with where I have the csv file located? Due to restrictions with our CMS I can only reference the file like this www.example.com/csvfile.csv.
Any help would be greatly appreciated.
Here is sample code for reading csv file into array
var request = new XMLHttpRequest();
request.open("GET", url, false);
request.send(null);
var csvData = new Array();
var jsonObject = request.responseText.split(/\r?\n|\r/);
for (var i = 0; i < jsonObject.length; i++) {
csvData.push(jsonObject[i].split(','));
}
// Retrived data from csv file content
console.log(csvData);
Here is the working fiddle example: http://jsfiddle.net/BdCnm/450/
Give this link a try and check his source code on Github, he lays it out in a pretty concise way.
https://github.com/MounirMesselmeni/html-fileapi

JSON file cannot be found in javascript

I am attempting to load a JSON file from javascript but i keep getting the following error even though the path is correct
[HTTP/1.1 404 Not Found 2ms]
this is the code i am using to load it
loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'Assets/test.json', true); // Replace 'my_data' with the path to your file
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == 200) {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
window.onload = function () {
var canvas = <HTMLCanvasElement> document.getElementById('Can');
context = canvas.getContext('2d');
load = new preload.AtlasLoader();
load.loadJSON(init);
}
function init(response) {
image2 = JSON.parse(response);
}
thanks in advance
i found the answer in this thread:
https://stackoverflow.com/questions/19516829/allow-loading-of-json-files-in-visual-studio-express-2013-for-web
it was a configuration issue with IIS and you just need to add the lnes posted in the answer in that question.

AJAX div not updating without alert call with error: b.data is undefined

First of all, any suggestions on rewriting my title?
Issue:
I have an AJAX updatable div, when my error checking alert calls are in, everything works perfect. But when I remove a specific one, the DIV never gets updated. I know it sounds confusing, but code is as follows, and then I will explain further.
AJAX SCRIPT
var xmlhttp
/*#cc_on #*/
/*#if (#_jscript_version >= 5)
try {
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")
} catch (e) {
try {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
} catch (E) {
xmlhttp=false
}
}
#else
xmlhttp=false
#end #*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp=false
}
}
function myXMLHttpRequest() {
var xmlhttplocal;
try {
xmlhttplocal= new ActiveXObject("Msxml2.XMLHTTP")
} catch (e) {
try {
xmlhttplocal= new ActiveXObject("Microsoft.XMLHTTP")
} catch (E) {
xmlhttplocal=false;
}
}
if (!xmlhttplocal && typeof XMLHttpRequest!='undefined') {
try {
var xmlhttplocal = new XMLHttpRequest();
} catch (e) {
var xmlhttplocal=false;
alert('couldn\'t create xmlhttp object');
}
}
return(xmlhttplocal);
}
function sndReq(page,key,includesDir,changeDiv,parameterString) {
var divToChange = document.getElementById(changeDiv); // the Div that the data will be put into
// Place loading image in container DIV
divToChange.innerHTML = '<div class="loading">Loading</div>';
if (includesDir == 1){
//Find Current Working Directory. Use to find path to call other files from
var myloc = window.location.href;
var locarray = myloc.split("/");
delete locarray[(locarray.length-1)];
var arraytext = locarray.join("/");
xmlhttp.open("POST","AJAXCaller.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(parameterString);
} else {
}
xmlhttp.onreadystatechange = handleResponse(changeDiv);
xmlhttp.send(null);
}
function handleResponse(changeDiv) {
/* ======== If I remove the following line script halts ================*/
/* ======== If line stays here, script executes perfectly ==============*/
alert('to changetext 1\n'+xmlhttp.responseText);
/* =========End of line removal issue =================================*/
if(xmlhttp.readyState == 4){
if (xmlhttp.status == 200){
var response = xmlhttp.responseText;
var update = new Array();
if(response.indexOf('|') != -1) {
update = response.split('|');
changeText(update[0], update[1]);
} else {
changeText(changeDiv, response);
}
} //End IF xmlhttp.status == 200
}
}
function changeText( div2show, text ) {
// Detect Browser
var IE = (document.all) ? 1 : 0;
var DOM = 0;
if (parseInt(navigator.appVersion) >=5) {DOM=1};
// Grab the content from the requested "div" and show it in the "container"
if (DOM) {
var viewer = document.getElementById(div2show);
viewer.innerHTML = text;
} else if(IE) {
document.all[div2show].innerHTML = text;
}
}
When I check my Firefox error console, this error ONLY appears when I remove that alert as defined in the code:
Timestamp: 5/30/2012 5:07:55 PM
Error: b.data is undefined
Source File: http://cdn.sstatic.net/js/wmd.js?v=cfd2b283af83
Line: 92
I am an advanced PHP/mySQL developer, but have been trying hard to grasp AJAX/JavaScript. Doing tutorials like mad. So please be descriptive in comments/answers so I can use them as a reference for learning...
Why would displaying an alert box alter code execution (for the better!) in any way?
NEW ERRORS - Google Chrome and Firefox Console (sigh...)
Uncaught Error: INVALID_STATE_ERR: DOM Exception 11
sndReqAJAX.js:89
element.onclick
Line 89 is the following (verified by Google Chrome Console)
xmlhttp.send(null);
Everything I find on the web refers to extremely complex issue regarding DOM objects not existing... This wouldn't apply here, would it?
First, the problem. This is the line:
xmlhttp.onreadystatechange = handleResponse(changeDiv);
The reason this is wrong is that xmlhttp.onreadystatechange should be a function - you need to assign a function to the property, what you are doing is calling the function and assigning the return value to the property. This is not in itself a problem, as long as your function returns a function. Which it doesn't.
If you're used to working with PHP (especially if your used to working with PHP <5.3) you may not be used to this concept. Javascript has support for closures in a way that anyone who doesn't use them much will find confusing.
What the line needs to look like is this:
xmlhttp.onreadystatechange = handleResponse;
By appending (changeDiv) you are calling the function, whereas what you need to do is simply pass it, like you would any other value.
Now, where it gets complicated is that you want to pass an argument that is local to the scope of the calling function. There are a number of ways to handle this, but a cursory look at your code tells me that handleResponse() is not used anywhere else, so it would be better to define this as a closure and not litter the global scope with a named event handler. This also overcomes the variable scoping problem:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
var response = xmlhttp.responseText;
var update = []; // "new Array()" is baaaad
if (response.indexOf('|') != -1) {
update = response.split('|');
changeText(update[0], update[1]);
} else {
changeText(changeDiv, response);
}
} //End IF xmlhttp.status == 200
}
};
Replace the aforementioned offending line with that block of code, and remove the handleResponse() function definition, and that should solve the immediate problem. Now, as to why the alert() "fixes" your original code - this is a little hard to explain, but I shall have a go... give me a minute to inspect the code properly
Attempt at a full and comprehensible explanation abandoned. If anyone wants one, post a comment and I'll have another go at it when I've had some sleep...

Categories

Resources