Read CSV file with Javascript into a key value pair array - javascript

There are plenty of examples of reading a CSV file using jQuery however javascript examples are few and far between.
As i am using an internal script editor for a particular application, i am limited to using Javascript only.
I have a csv file that has headings followed by data in each row.
Heading1,Heading2,Heading3,Heading4
row1data1,row1data2,row1data3,row1data4
row2data1,row2data2,row2data3,row2data4
The delimiter being used is , however there could be others e.g. ^.
As i can't upload a file, i have the option to manually reference an absolute path.
Is there a way i can use only javascript to read a csv file?

As a start, here is a couple of ways to read a file with javascript
HttpRequest: (from web server or absolute path)
Source: Javascript - read local text file
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);
}
And specify file:// in your filename when using an absolute path
readTextFile("file:///C:/your/path/to/file.txt");
FileReader API:
Source:
- http://codepen.io/matt-west/pen/KjEHg
- http://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api
HTML
<div id="page-wrapper">
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
JS
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
JS on MS Windows (simple sample)
Source: http://msdn.microsoft.com/en-us/library/czxefwt8(v=vs.84).aspx
function ReadFiles()
{
var fso, f1, ts, s;
var ForReading = 1;
fso = new ActiveXObject("Scripting.FileSystemObject");
ts = fso.OpenTextFile("c:\\testfile.txt", ForReading);
s = ts.ReadLine();
// s holds the text content
ts.Close();
}

Related

Is there a way to pull data from a txt file and make it update everytime the txt file is updated?

Is there a way to pull data from a txt file and make it update everytime the txt file is updated? I'm using the following code in my program and it will find the file and display its content fine but when I update the txt file, the program does not update the new text.
function OnFileLoad()
{
var file = document.getElementById("FileReader").files[0];
var fileDisplayArea = document.getElementById("FileContent");
if (file.type.match('text.*|image.*|application.*'))
{
console.log('hello. we are inside the function')
var reader = new FileReader();
reader.onload = function (e)
{
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
}
else
{
fileDisplayArea.innerText = "File not supported!"
}
}

Reading uploaded text file contents in variable

I want to read string from text file and save it in variable . What I did:
HTML:
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
JS:
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
var newString;
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
newString=reader.result; //SAVE RESULT
alert(newString);
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
I want to save text from file and alert it. But it doesnt work.
I did it:
var tfile;
var reader = new FileReader();
function rdfile(files)
{
tfile = files[0];
reader.readAsText(tfile, 'CP1251');
reader.onload = function(e)
{
str = e.target.result;
alert(str);
};
}
But it doesnt work too. I alert many different symbols but not my text.
Look at your code from your first attempt:
newString=reader.result; //SAVE RESULT
alert(newString);
reader.readAsText(file);
Get the result
Alert it
Do the thing that generates the result
You have to read the file before you can look at the text you get from reading it!
Move steps 1 and 2 in to the onload event handler you already have.
Now look at your second attempt. You never call rdfile and you never call readAsText.

How can I use filereader to parse csv file and convert it into an array?

I have this in my html page:
<input type="file" id="fileInput" />
and this in my javascript page:
window.onload = function () {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function (e) {
// code that handles reading the text file
var file = fileInput.files[0];
var textType = /text.*/;
// checks if the file is a text file
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function (e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!";
}
});
}
I want to be able to convert the Filereader into an array so I can do something like:
document.getElementById("today").innerHTML = today[0];
Is this possible? I also don't think this is the way to read a csv file using filereader.
UPDATE: I have figured out how to get the csv file and turn it into an array by the following code:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "data.csv",
dataType: "text",
success: function (data) { processData(data); }
});
function processData(csv) {
var temp = new Array();
temp = csv.split(",");
document.getElementById("today").innerHTML = temp[0];
}
});
Now I am wondering if there is a way to use FileReader() so I can select the file from the html page instead of using url: "data.csv" so I can select multiple files.
You can handle this a few ways. You might think to ajax the file to a PHP script, then do something like $csvData[] = fgetcsv($file). Then you can echo json_encode($csvData);. It may be an extra http/server request but processing files is much easier.
There are some Javascript libraries that you wouldn't need to run server-side scripts for - JQuery CSV and PapaParse

how to get a filename in HTML and use it in D3.js (javascript)?

I've written a d3 script that plots some data and in which the path to the input file is hard coded.
I'd like to be able to select the file by browsing on my computer and then passing it to the script.
<body>
<!--locally browse to get the filename-->
<input type="file" id="input">
<script src="http://d3js.org/d3.v3.js"></script>
<script>
// Get the data
d3.tsv("#input", function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});
// then the code that plots etc....
</script>
</html>
1) Create the input select button and register it to a file select handler function:
var input = d3.select("body").append("input")
.attr("type","file")
.on("change", handleFileSelect)
2) The file select handler will register a new function with the fileHandler as input on the onload callback:
// Single file handler
function handleFileSelect() {
// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
// Great success! All the File APIs are supported.
} else {
alert('The File APIs are not fully supported in this browser.');
}
var f = event.target.files[0]; // FileList object
var reader = new FileReader();
reader.onload = function(event) {
load_d3(event.target.result)
};
// Read in the file as a data URL.
reader.readAsDataURL(f);
}
3) Crete a function with a fileHandler as input, that calls your D3 code (d3.json in this example. You can adapt it for tsv)
function load_d3(fileHandler) {
d3.json(fileHandler, function(error, root) {
//do stuff
};
};
Hope this helps.
Subscribe to input file change event. Then use FileReader to get content of selected file, then parse it using d3.tsv.parse
You can use d3.csvParse to parse the result after reading file. Here's my working code:
<input type="file" id="input" onchange="handleFiles">
<script>
const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
const fileList = this.files; /* now you can work with the file list */
var file = fileList[0];
var reader = new FileReader();
reader.onload = function(e) {
// The file's text will be printed here
console.log(e.target.result);
console.log(d3.csvParse(e.target.result));
};
reader.readAsText(file);
}

replace XMLHttpRequest in javascript

I used to read my local files using XMLHttpRequest.
function getData(fileName)
{
var filePath = fileName;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", filePath, false);
xmlhttp.send(null);
var fileContent = xmlhttp.responseText;
var tempArr = csv2Arr(fileContent);
var returnLabelArr = tempArr[0].toString().split(',');
tempArr.shift();
var returnDataArr = tempArr;
return { 'dataArr' : returnDataArr, 'labelArr' : returnLabelArr };
}
fileName starts with "C://..." and my program works on browser with address "file:///...".
But, without "--allow-file-access-from-files" tag, my code doesn't work on Chrome. And also it doesn't work on IE and Firefox without changing some security options.
So, I tried to jquery API like this,
function getData(fileName)
{
var filePath = fileName;
var fileContent;
$.ajax({
type: "GET",
url: filePath
})
.done(function(data) {
alert(data);
fileContent = data;
});
var tempArr = csv2Arr(fileContent);
var returnLabelArr = tempArr[0].toString().split(',');
tempArr.shift();
var returnDataArr = tempArr;
return { 'dataArr' : returnDataArr, 'labelArr' : returnLabelArr };
}
The Problem also occurs. I think Same-origin policy prevents it.
Can anyone give me some suggestions for me to access local files without changing security options? Should I use some plug-ins to solve this?
Please let me know.
Thank you.
If you can use <input type="file"> to select files, then the solution is:
HTML:
<form action="">
<input type="file" id="file-input" multiple="multiple" accept="image/jpeg" />
</form>
JS:
var fileInput = document.querySelector('#file-input');
fileInput.addEventListener('change', function(event) {
var files = fileInput.files;
if (files.lenght == 0) {
return;
}
for(var i = 0; i < files.length; i++) {
readFile(files[i]);
}
fileInput.value = "";
}, false);
var readFile= function(file) {
var reader = new FileReader();
reader.onload = function(e) {
var dataUrl = e.target.result;
// now, load the data into some element
// if this is image, you can do this:
var image = new Image();
image.src = dataUrl;
document.body.appendChild(image);
};
reader.readAsDataURL(file);
};
Also, discover the FileReader API to find out, how you can use it otherwise, as it has more methods to read data.

Categories

Resources