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.
Related
I am using Evan plaice jquery-csv libary but I am running into a lot of trouble to get it working at the moment due to his code not updated after google code is deprecated.
I am using the one of his example where you upload a csv file and it will parse the document so that the csv file will be shown on the webpage Demo here.
I downloaded his code from github but then since the googlecode he imported is not working anymore I put the file jquery.csv.js in the same folder as the file I am using. In the jquery.csv.js, there is a function being called which is toArray in the html file. I deleted the line where it is used to be <script src="http://jquery-csv.googlecode.com/git/src/jquery.csv.js"></script> and added <script type="text/javascript" src="./jquery.csv.js"></script> However, for whatever reason it complains that toArry is not defined.
Basically the code is like this:
function printTable(file) {
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event){
var csv = event.target.result;
var data = $.csv.toArrays(csv); << The line that has problem.
var html = '';
for(var row in data) {
html += '<tr>\r\n';
for(var item in data[row]) {
html += '<td>' + data[row][item] + '</td>\r\n';
}
html += '</tr>\r\n';
}
$('#contents').html(html);
};
reader.onerror = function(){ alert('Unable to read ' + file.fileName); };
}
In the developer console it indicates:
Uncaught TypeError: Cannot read property 'toArrays' of undefined
at FileReader.reader.onload (file:///Users/Jace/Downloads/jquery-csv-master/examples/file-handling.html:75:25)
I think you're problem is that when you removed the reference to the jquery-csv library hosted on Google Code and included your local version, you put it above the reference to jQuery itself. That's when I notice the error you're describing. The order you load in your JavaScript files does matter. When for example JavaScript code in file B.js is depending on code in A.js, A.js needs to be specified before B.js.
So basically check if the order you're specifying the files in in your HTML file is correct:
<body>
<!-- HTML... -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="jquery.csv.js"></script> <!-- The "./" is not used here -->
<script>
// Code...
</script>
</body>
Also, the ./ in front is not needed and not common. I've never used it in any case. ;)
I hope that makes it a bit more clear to you!
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])
});
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.
How to read text file (text1.txt) from current directory using javascript without jquery. I tried the following code.
var file = "text1.txt";
var reader = new FileReader();
var result = reader.readAsText(file);
console.log(result);
The FileReader API is usually used to read files selected via the an <input type="file">. It cannot read arbitrary files. The readAsText method expects to receive with a Blob or a File object, not a string containing a file name.
To read files that are siblings of the HTML document, use XMLHttpRequest. This will reliably work if you load the document over HTTP(S). If you are using a local HTML document (via a file: URI) then security restrictions in many browsers will prevent it from working (and you should run a local web server instead).
Option A, Your use-case prevents you from using an http or php server.
You can include local content in your javascript as a variable using a script include. If you are opening the page locally, as a file from a directory, this is the only way to include local content in the web page.
To include local content, put this above your other script tag:
<script src="text1.txt"></script>
and edit your text1.txt file so it assigns all the content to a variable:
gbl_text=`...contents of my text file...
...more contents...
...and so on....
`
You can use a script to create this include file, for example (use the ` tick mark below the tilde ~ key):
echo -n "var gbl_text=\`" > text1.txt
cat your-original-file.txt >> text1.txt
echo "\`" >> text1.txt
Then use the gbl_text variable in your javascript as needed...
function dosomething()
{
if (typeof(gbl_text)=='undefined'){
setTimeout('dosomething()',500) //call back until defined
}else{
console.log(gbl_text)
}
}
Option B, Your use-case would allow you to use the php-cli built-in server.
If you are able to run php-cli, you can open the page on the built-in php webserver, and read and write local content with a php call. To install and use php on linux,
sudo apt install php7.0-cli
#To use the php built-in webserver, run:
php -S localhost:8000 -t /path/to/your/content
So, instead of opening your html as a file, you would open as an http web page:
firefox http://localhost:8000/mypage.html
#or browser of choice
Now the local webpage is being served by an actual (local) http server with php support, and you can manipulate local files with it.
Here is simple example showing how to read and write to a local file using jQuery and php. Download and include jQuery (see jQuery.com) in your html file.
Contents of dofile.php:
<?php
$dowhat = $_REQUEST['dowhat'];
if ($dowhat=='save'){
$myvar = $_REQUEST['myvar'];
file_put_contents('myfile', $myvar);
}elseif($dowhat=='read'){
$myvar=file_get_contents('myfile');
echo $myvar;
}
?>
Contents of mypage.html:
<script src='jquery-3.2.1.js';></script>
<!--make sure the filename matches the jQuery you use-->
<script>
function savevar(){
var myvar=document.getElementById('mytxt').value
var path="dofile.php?dowhat=save&myvar="+myvar
$.get(path, function(data){
console.log("saved ...\n"+myvar)
alert("saved ...\n"+myvar)
});
}
function clearbox(){
document.getElementById('mytxt').value='reading file...'
setTimeout('getvar()',1000)
}
function getvar(){
var path="dofile.php?dowhat=read"
$.get(path, function(data){
console.log(data);
document.getElementById('mytxt').value=data
/*do other things with data here*/;
});
}
</script>
<html>
Type something in the text box.<br>
Use the Read and Write buttons to verify <br>
text is saved and read back.<br>
<input id='mytxt' value='type text here' onclick=document.getElementById('mytxt').value=''><br>
<input type='button' value='Save' onclick=savevar() ><input type='button' value='Read' onclick=clearbox() >
</html>
Please distinguish 2 kinds of reading files:
reading "from internet" - use XMLHttpRequest to read any kind of file
reading "from client" - use FileReader or <input type="file">
make a tiny iframe.
load the file there.
read it with iframe.innerHTML
I need to load a simple .CSV file from JS (That's not the problem here), but the "script" need to be portable (i will use it as the screen on a competition), and score data will be inserted in the CSV, and JS will be updating it's data based on the CSV.
But my problem here is: I need to run it without apache or a server, because i cant make shure the people who will use it, will have apache and also Internet... It need to be opened from a folder (Just a HTML with JS, and a file in the same folder with the .CSV)
When i try to access files from jQuery ($.get(..., ..., "jsonp"), and $.get()), Chrome output this error:
XMLHttpRequest cannot load file:PATHTOTHEFILE Origin null is not allowed by Access-Control-Allow-Origin.
This happens because the browser blocks it's content (for security reasons).
How can i "deal" with this problem, or do you know a better solution, to save some simple data and read it from JS without secury problems?
Thanks
you need to add --allow-file-access-from-files to the chrome startup command line
make a BAT file and get you users to click that to start your app
%LOCALAPPDATA%\Google\Chrome\Application\chrome.exe ^
--allow-file-access-from-files ^
http://bing.co.uk
swap out the http:// for you file url.
You can use html5 FileReader. But in this way you have to select file.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<label for="files">Path to file: </label><input type="file" id="files" name="files[]"/>
<script>
function handleFileSelect(evt) {
var files = evt.target.files;
var f;
for (var i = 0; f = files[i]; i++) {
if (!f.type.match('text.*')) {
continue;
}
var reader = new FileReader('test.html');
reader.onloadend = (function () {
return function(e) {
alert(e.target.result);
};
})();
reader.readAsText(f);
}
}
var fileSerf= document.getElementById('files');
if (fileSerf){
fileSerf.addEventListener('change', handleFileSelect, false);
}
</script>
</body>
</html>
example: http://jsbin.com/ozeyag/293/