Reading CSV file in to an array using javascript - 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

Related

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

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

How to extract single element line by line and store in an array in Javascript?

I've got a text file 'mytext.txt' with IPs and some text seperate by commas in different lines -
24.16.153.165:51413,abc
67.185.72.127:51413,xyz
69.247.183.46:63303,pqr
130.56.220.16:6881,def
I want to store the IPs in an array in JavaScript to plot them on a map. I found a way to do this by using a static array -
var map = new google.maps.Map(document.getElementById('map'), googleMap);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(infowindow, "closeclick", function() {
map.fitBounds(latlngbound);
map.panToBounds(latlngbound)
})
var ipArray = ["70.177.167.189", "123.135.107.115", "123.135.107.115", "123.135.107.115", "123.135.107.115", "122.182.6.19", "24.19.187.145", "24.19.187.145", "27.251.20.130", "27.251.20.130"];
ipArray.forEach((ip) => {
addIPMarker(ip);
})
} catch(e){
//handle error
}
Can someone tell me how to do it after extracting the IPs from the text file? It should be a fairly simple logic, but I'm not very familiar with JavaScript. Thanks!
This function works if you have a file on the server or another url.
function loadDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = this.responseText;
var data = myObj.split(/\n/g);
var data_ip = [];
for(item in data)
{
var ip = data[item].split(/,/g);
data_ip.push(ip[0]);
}
console.log(data_ip);
}
};
xmlhttp.open("GET", "file.txt", true);
xmlhttp.send();
}
And this was work with a locally stored file.
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 myObj = rawFile.responseText;
var data = myObj.split(/\n/g);
var data_ip = [];
for(item in data)
{
var ip = data[item].split(/,/g);
data_ip.push(ip[0]);
}
console.log(data_ip);
}
}
}
rawFile.send(null);
}
readTextFile("file:///C:/your/path/to/file.txt");
To read a file in from your system you need to use the fs (file system) module provided by Node. You won't need to do any npm install.
JavaScript file:
const fs = require('fs');
const mapData = fs.readFileSync(//path to file here);
// do things with the data like your ip mapping, etc...
I have used the fs.readFileSync() function in the example but you will want to read the documentation and see what works best for your application.
Documentation:
https://nodejs.org/api/fs.html

xmlhttp.open multiple XML files

How would I go about fetching multiple XML files? I tried creating an array but that only opens the last file, and as I understand it xmlhttp.open is supposed to cancel any previous send. I tried modifying this which was the closest thing I could find, but my JavaScript knowledge is a bit to limited to adapt it.
This is the basic code I'm using to get one XML file.
if (window.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest();
}
xmlhttp.open("GET","myfile.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("TAGNAME");
for (i=0;i<x.length;i++)
{ // Further parsing
}
Also is it possible to then display which file the parsed content comes from in my loop?
try this:
var arr = ["file1.xml", "file2.xml"],
cnt = 0, xhr = new XMLHttpRequest(), method = "GET";
function formatXml(file, xmlDoc) {
var x=xmlDoc.getElementsByTagName("TAGNAME");
console.log(file,x);
}
function getXml() {
xhr.open(method, arr[cnt], true);
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
formatXml(arr[cnt], xhr.responseText);
cnt++;
if (cnt < arr.length) getXml(); // call again
}
};
xhr.send();
}
getXml(); // start it

JSON Parse File Path

I'm stuck trying to get the correct path to the local file. I have the following directories:
Resources ->
data ->
file.json
js ->
folder ->
script.js
html ->
folder ->
file1.html
I'm executing script.js from file1.html, with js code:
var answers = JSON.parse('../../data/file.json');
alert(answers);
But it doesn't work, even alert is not starting.
What is wrong?
Also I've tried this:
function readJSON(file) {
var request = new XMLHttpRequest();
request.open('GET', file, false);
request.send(null);
if (request.status == 200)
return request.responseText;
};
var temp = readJSON('../../data/file.json');
alert(temp);
Alert undefined in this case.
Since it is in the directory data/, You need to do:
file path is '../../data/file.json'
$.getJSON('../../data/file.json', function(data) {
alert(data);
});
Pure JS:
var request = new XMLHttpRequest();
request.open("GET", "../../data/file.json", false);
request.send(null)
var my_JSON_object = JSON.parse(request.responseText);
alert (my_JSON_object.result[0]);
This solution uses an Asynchronous call. It will likely work better than a synchronous solution.
var request = new XMLHttpRequest();
request.open("GET", "../../data/file.json", false);
request.send(null);
request.onreadystatechange = function() {
if ( request.readyState === 4 && request.status === 200 ) {
var my_JSON_object = JSON.parse(request.responseText);
console.log(my_JSON_object);
}
}
Loading local JSON file
Use something like this
$.getJSON("../../data/file.json", function(json) {
console.log(json); // this will show the info in firebug console
alert(json);
});
var request = new XMLHttpRequest();
request.open("GET","<path_to_file>", false);
request.send(null);
var jsonData = JSON.parse(request.responseText);
This code worked for me.
If Resources is the root path, best way to access file.json would be via /data/file.json
My case of working code is:
var request = new XMLHttpRequest();
request.open("GET", "<path_to_file>", false);
request.overrideMimeType("application/json");
request.send(null);
var jsonData = JSON.parse(request.responseText);
console.log(jsonData);
Even if long time answerd, I here is another that does not need to create a request. I created a lg.js script containing a class and some functions (setLg, de, en, ...)
Each "lg" function (de, en, fr, ...) provides a json object containing the translations.
"use strict"
class Lg {
constructor() { this.tr = this.en(); }
setLg(l) {
if l == "de" this.tr = this.de();
if l == "en" this.tr = this.en();
de() {
"item": "Artikel",
"login": "Login"
}
en() {
"item": "Item",
"login": "login"
}
}
var lg = new Lg(); //global accessable object
You can then use it by "lg.tr.item"
You could also create a small function, that checks if the "key" is in the JSON object to have some kind of error checking.

reading a text file line by line using javascript

I am trying to read in lines from a text file that are in this form;
34.925,150.977
35.012,151.034
34.887,150.905
I am currently trying to use this methodology, which obviously isn't working. Any help would be appreciated.
var ltlng = [];
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "C:\Gmap\LatLong\Coordinates.txt", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) {
if (txtFile.status === 200) { // Makes sure it's found the file.
lines = txtFile.responseText.split("\n"); // separate each line into an array
ltlng.push(new google.maps.LatLng(lines.split(",")[0],lines.split(",")[1]); //create the marker icons latlong array
}
}
}
XMLHttpRequest works when resources are called by HTTP/S protocol (and not file protocol, as in your example)
So to make your code work, you should try this code along with a web server

Categories

Resources