I have a standard folder structure for a web app.
css
js
img
asetts
lib
index.html
Inside my assets folder I have a bunch of plain text files and I would like to first be able to list the filenames using Javascript, so I can store the URI's in the model, and read from them later on the in the application. I want all of this happening client side.
(Client-side) JavaScript does not have access to the file system like that.
This is not possible without some kind of browser plugin.
You can read the textfiles in the local folder.
function read()
{
var xHR = new XMLHttpRequest();
//replace textfile_url with the relative url of your text file
xHR.open("GET", "textfile_url", true);
xHR.onreadystatechange = function ()
{
if(xHR.readyState === 4)
{
//all your text is in the next line
var text = xHR.responseText;
}
}
xHR.send();
}
Related
I'm just trying on the task, file manipulation system using java script. As I was referred from W3C File API( https://www.w3.org/TR/FileAPI/ ), we can only read local files like
var file = "test.txt";
function readTextFile(file) {
var readFile;
if(window.XMLHttpRequest){
// for new browsers
readFile = new XMLHttpRequest();
}else{
//for old browsers like IE5 or IE6
readFile = new ActiveXObject("Microsoft.XMLHTTP");
}
readFile.open("GET", file, true);
readFile.onreadystatechange = function() {
if(readFile.readyState === 4) {
if(readFile.status === 200 || readFile.status == 0) {
//text will be displayed that read from the file
console.log(readFile.responseText);
}
}
}
readFile.send(null);
}
but it looks there is no options to write on file without server. I was tried to fetch solutions from the websites like http://www.stackoverflow.com/, the study says almost there is no possibilities.
For an example what I got is
from https://gist.github.com/Arahnoid/9925725
It shows error "TypeError: file.open is not a function."
So my question is, Is there any possible to file manipulations(asking only about Write file) for local files without using server-side scripting or is any extensions like available?
We can do file manipulations using server scripting languages such as PHP, Node.js.
Thanks in advance.
In your code, it's not reading from the local file (test.txt), it's sending Ajax GET request to server and read file in server side.
To read local file (files that stored in machine where browser is installed), you need to use FileAPI, which is not used in current code.
To write file to local, it's impossible to write it directly using JavaScript. Otherwise, it would be a huge security vulnerability. However, you can generate a URL from File object, and use that URL as the href attribute of <a> tag, so that user can download and "write to local" manually.
Here is a code snippet to read & "write" local file:
var inputElement = document.getElementById("input");
var reader = new FileReader();
var downloadLink = document.getElementById('downloadLink');
reader.onloadend = function(){
console.log(reader.result);
}
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
var fileSelected = this.files[0]; /* now you can work with the file list */
reader.readAsBinaryString(fileSelected);
downloadLink.href = window.URL.createObjectURL(fileSelected);
}
<input type="file" id="input">
<a id="downloadLink" download>Download</a>
I'm developing an application in Javascript, which requires to read a text file and put it into a variable as input. However, I google many related questions and found that FileReader can't read file without file input because of security reason. Is there any library or dirty ways to read the content of a text file with only local path? Thanks a lot.
I think a way to do it would be to load your file with Ajax. Then you can do whatever you want with its content.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Do whatever you want here with this.responseText
}
};
xhttp.open("GET", "youtext.txt", true);
xhttp.send();
It's easier to put your file.txt or file.json to your localhost, or put it on your server.
or this link maybe can help you out
https://github.com/nwjs/nw.js/issues/3227
i understand this question that he want to read file line by line from his local path.
I currently have javascript code (please see below) that searches an array for a month/day combination, and if it is found, assigns the name of a .jpg file (which is used for the background image of a page). Instead of hard-coding all of the data in the array, I'd like to be able to create an external .txt file with month/day codes and associated image file names, that could be read and loaded into the array. Thanks for your help!
var ourdates = ['0000','0118','0215','0530','0614','0704','0911','1111','1207']
if (ourdates.indexOf(monthday) != -1)
{
ourimage = "flag";
}
If you mean loading it from your server, that's a classic use-case for ajax, frequently combined with JSON:
var ourdates = null;
var xhr = new XMLHttpRequest();
xhr.open("GET", "/path/to/your/data");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
ourdates = JSON.parse(xhr.responseText);
// call something that uses `ourdates`
}
};
xhr.send(null)
If you mean from the user's computer, my answer here shows how to do that with the File API. Doing that requires an <input type="file"> input (or drag-and-drop event) that the user uses to grant access to the file to your script. You can't read a file from their machine without them specifically giving you access to the file.
I want to load a json-stringified file in my javascript. The javascript reside in a html-file which I load from my local file system.
I have tried with the following code:
var xhr = new XMLHttpRequest();
xhr.open('GET', fileName, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
// get binary data as a response
var blob = this.response;
alert("Yo");
}
};
But the onload event fires only once, with the status=0, then no more happens.
I have tried to use both a full path to the file as well as a local file path like "/files/the_file.txt".
It looks like the problem is related with me trying to run the html file locally. I don't want to set-up a local server as I have seen proposed in similar posts here at so.
Anyone out there with a solution to this problem?
EDIT:
This is not what I want, but this might serve to give an example of how I almost want it. This example let the user select a file, and my script can now access the content of the selected file.
HTML:
<input type="file" id="FancyInputField" onchange="doIt();">
Javascript:
function doIt(){
var selectedFile = document.getElementById('FancyInputField').files[0];
reader = new FileReader();
reader.onload = function (e) {
var output = reader.result;
var daObject = JSON.parse(output);
}
reader.readAsText(selectedFile);
}
This also works with a local html file. (No local server)
My question stands; How do I read the file(s) with no user interaction? The files reside in a sub-folder to where the html file are located. I can with no problem load and show an image from the same sub-folder, with an <img> tag. ..So why is it so difficult to load a text file?
How do I read the file(s) with no user interaction?
You can't. Those files belong to the user, not your website. You can't choose to read them.
I can with no problem load and show an image from the same sub-folder, with an <img> tag
There is a lot of difference between displaying an image to the user, and making the content of a file available to JavaScript code written by the page author.
So why is it so difficult to load a text file?
Send someone an HTML document in an email
Enjoy the JavaScript in it scooping up files from the hard disk and sending them to Joe Evil Hacker's server
It's just basic security.
Use URL.createObjectURL(file), instead of ajax.
I have seen similar questions here but I just can't understand them.
I am building a small web page and I want to read a .json file from my file system and get the object in it.
The web page is also local and the .json file is in the same folder as the .html file.
How to do that on my Ubuntu machine without using any servers and without jquery if it is possible?
Here's some vanilla javascript XMLHTTPRequest code, which does take into account the IE quirks of ActiveX objects:
var useActiveX = typeof ActiveXObject !== 'undefined';
function loadJSON(file, callback) {
var xobj;
if (useActiveX) {
xobj = new ActiveXObject('Microsoft.XMLHTTP');
} else {
xobj = new XMLHttpRequest();
}
xobj.callback = callback;
if (xobj.overrideMimeType) {
xobj.overrideMimeType('application/json');
}
xobj.open('GET', file, false);
xobj.onreadystatechange = function() {
if (this.readyState === 4) {
this.callback(this);
}
}
xobj.send(null);
}
Then you just run it by feeding it a filepath and a callback function:
loadJSON('filename.json', function(obj) {
alert(obj.responseText);
}
You can simply append a <script> tag to your page, pointing the SRC to the local .js file in the same folder. You don't need to use Ajax.