How to parse CSV from file with PapaParse? - javascript

I can't find a single bit of information about how to do this, so I'm resorting to asking a question here.
How do I actually load a local file and parse it using PapaParse?
I currently have:
$(function() {
Papa.parse(new File("text.csv"), {
complete: function(results)
console.log("Finished:", results.data);
}
});
});
...but I have decided the constructor must be intended for creating new files. How am I supposed to do this? PapaParse's website shows this:
Papa.parse(file, {
complete: function(results) {
console.log("Finished:", results.data);
}
});
...buuut that doesn't explain where file came from.

You need to read the file from the system before trying to parse it.
If you are trying this in a web application, you could add a file uploader and call Papa.parse() after an event: i.e. either when file changes, or at the click of a button.
<input type="file" id="fileInput" />
Then you need to add an onchange or onclick event function accordingly.
Inside the event function, you can access the file as:
event.target.files[0]
If you are using this on a server, you can use any filesystem methods to read your file.
Like in Node.js we have fs.readFile() function to read a file from the system at a given path.

Related

How to define a local file as a DOM object?

I want to parse data in my computer using JavaScript. I use papa parse .
In PapaParse documentation it has been stated local files can be parsed by following code ;
Papa.parse(file, config)
In documentation they say file is a File object obtained from the DOM. How can I define a local file as an DOM object ?
I doubt that this is possible as it would be a huge security problem. Imagine someone could just read files from your computer when you load their javascript through your browser. You'll have to go with a file picker.
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<input type="file" id="csv-files" multiple>
<script>
var handleFileSelect(evt) {
var file = evt.target.files[0];
// do stuff with that file e.g. Papa.parse(file)
}
$(document).ready(function() {
$("#csv-files").change(handleFileSelect);
});
</script>
the above code uses jQuery to load the files when the file picker was used.
see joyofdata.de/parsing-local-csv-file for reference. Concise explanation.

Loading CSV file with AlaSQL and JQuery

I'm building an HTML based app for querying imported CSV file using AlaSQL. I started with this demo and tried to implement the same behavior by setting the onChange event through JQuery rather than in the tag. I basically follow the same pattern, and naively pass the event forward to the loadFile method. Alternatively, I tried just handling the alasql request right in the callback.
html:
<input id="with-jquery" name="with-jquery" type="file" />
javascript:
$('#with-jquery').on('change', function(event)
{
console.log('in jquery callback');
filename = $('#with-jquery').val();
console.log("filename: " + filename);
alasql('SELECT * FROM FILE(?,{headers:true})',[event],function(res){
console.log('in alasql callback');
data = res;
console.log(res);
document.getElementById("jquery-result").textContent = JSON.stringify(res);
});
//loadFile(event);
});
http://plnkr.co/edit/FOWwVsW7zAUGwv3BDBdN?p=preview
When I try to load the file using the JQuery handler, I get
in jquery callback
test.js:7 filename: C:\fakepath\sample.csv
alasql.min.js:13 Uncaught Error: Wrong usage of FILE() function
Here are some questions:
I can't find documentation for what alasql expects in the [event] slot.
How does the FROM FILE method relate to the more specific FROM CSV and FROM XLSX methods.
The wiki shows using the FROM CSV method by supplying a file name. I can't imagine how that would work without supplying the full path to a local file. But you can't get that from the browser.
The wiki also recommends using the "promise" format. How would I implement that here?

Access fileEntry after dropping a file in a Chrome App

Is it possible to get a fileEntry object in Chrome Apps by opening a file via Drag'n'Drop? When I drop a file into my app I only get a file object which seems to be unrelated to the file system. I can't use that object to save the file after changing it.
I get the file like this:
document.body.addEventListener('drop', function (event) {
file = event.dataTransfer.files[0]
});
What I want to do
I'm developing a text editor and I want to add a feature to open a file by dragging it into my app.
As I said: I already get the content of the file, but I can't write changes back to the file since I need a fileEntry object in order to do so.
Okay, I just found it while inspecting the event object. In the event object there's a function called webkitGetAsEntry() to get the fileEntry object. Here's the correct code:
document.body.addEventListener('drop', function (event) {
fileEntry = event.dataTransfer.items[0].webkitGetAsEntry();
});
This is the object you can use to write changes back to the file system.
Code for reference:
// Of course this needs the "fileSystem" permission.
// Dropped files from the file system aren't writable by default.
// So we need to make it writable first.
chrome.fileSystem.getWritableEntry(fileEntry, function (writableEntry) {
writableEntry.createWriter(function (writer) {
// Here use `writer.write(blob)` to write changes to the file system.
// Very important detail when you write files:
// https://developer.chrome.com/apps/app_codelab_filesystem
// look for the part that reads `if (!truncated)`
// This also is very hard to find and causes an annoying error
// when you don't know how to correctly truncate files
// while writing content to the files...
});
});

get file object using full path

is there a way to get a file object using the directory full path of the file itself? this piece of code wont work:
var file1 = new File("D:\\path\\to\\file\\file.txt");
I need to get the file object since I have a function that has a file object as its parameter.
bryan
That would be very tragic if browsers could suddenly start accessing users' file systems without their permission.
I would suggest using <input type="file">. This way the user chooses which file they will allow the browser to access.
I would suggest you to use: <input type="file" id="fileUpload"> and get the file name using
$('input[type=file]').change(function () {
console.log(this.files[0])
});

Read and display the text file contents upon click of button using Javascript

On click of a button called result, I want to read and display a text file (which is present in my local drive location say: C:\test.txt) using Javascript function and display the test.txt file contents in a HTML text area.
I am new to Javascript,can anyone suggest the code for Javascript function to read and display the contents of .txt file?
An Ajax request to a local file will fail for security reasons.
Imagine a website that accesses a file on your computer like you ask, but without letting you know, and sends the content to a hacker. You would not want that, and browser makers took care of that to protect your security!
To read the content of a file located on your hard drive, you would need to have a <input type="file"> and let the user select the file himself. You don't need to upload it. You can do it this way :
<input type="file" onchange="onFileSelected(event)">
<textarea id="result"></textarea>
function onFileSelected(event) {
var selectedFile = event.target.files[0];
var reader = new FileReader();
var result = document.getElementById("result");
reader.onload = function(event) {
result.innerHTML = event.target.result;
};
reader.readAsText(selectedFile);
}
JS Fiddle
Using $.ajax() function: http://api.jquery.com/jQuery.ajax/
$(function(){
$.ajax({
url: "pathToYourFile",
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
var resourceContent = data; // can be a global variable too...
// process the content...
}
});
});
As You've mentionned HTML, I assume you want to do this in a browser; Well the only way to access a local file in a browser is by using the File API, and the file can only be obtained via a user's manipulation such selecting a file in an <input type='file'> element, or drag&dropping a file in your page.
We could achieve this by, I should say, creating a virtual file!
Storing the contents of the text file into a Javascript string variable. However, one should consider all new lines and other special symbols\characters and etc.!
We than can markup a script tag in our HTML to load that *.js Javascript like this:
<script src="my_virtual_file.js"></script>
The only difference here is that a text file that could contain:
Goodnight moon
Follow the white rabbit
In a Javascript script string variable should look like this:
var my_virtual_file = "Goodnight moon\nFollow the white rabbit";
Later on, you can access this variable and treat it as you wish...
A programming language like Javascript that follows standards like ECMAScript, gives you a wide range of capabilities to treat and convert data from one type into another.
Once you have your Javascript script loaded, you can then access that variable by any button in your HTML by assigning a function call on its onclick attribute like this:
<button onclick="MyVirtualFile()"></button>
And ofcourse, you just add a script tag to your HTML, like this:
<script>
functiion MyVirtualFile(){
alert(my_virtual_file);
};
</script>
... or your may just create and import another Javascript script containing that same function, under your desire.
If you are concerned about how much information you can store into a Javascript string variable, just take a look at this interesting (and old as this one :D) SO thread.
Lets see if this snippet works :):
var my_virtual_file = "Goodnight moon\nFollow the white rabbit"
function MyVirtualFile(){
alert(my_virtual_file);
// Do anything else with your virtual file
};
<!DOCTYPE html>
<html>
<head>
<script src="my_virtual_file.js">
</script>
</head>
<body>
<h1>HTML Javascript virtual file</h1>
<button onclick="MyVirtualFile()">Alert my_virtual_file</button>
</body>
</html>
You can programatically access and dynamically change the contents of your Javascript script, but you should remind that you need to reload your HTML so the browser can load the new contents.
On your filesystem, you can just treat this *.js as a *.txt file, and just change its contents keeping in mind the Javacript.

Categories