How to read local text file in JavaScript automatically [duplicate] - javascript

This question already has answers here:
How to read a local text file in the browser?
(23 answers)
Closed 6 years ago.
I want to read a local text file from my local html file, so I tried to follow the solution in this thread Javascript - read local text file but the suggested solution does not work for me either:
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 allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
When I call the function readTextFile("file:///D:/test/text.txt"); no error does show up in firebug but no alert is shown neither. I use Windows und Firefox 51.0.1 (64-Bit).
I don't want to use the function FileReader() in combination with a button <input type='file' onchange='openFile(event)' ... since the text file needs to be read automatically when loading the page. So how can I make work the solution above?
Reading the thread linked it looks like others also have problems with that solution although the thread is marked as solved.

Complete HTML and JavaScript file as an example for reading client side data files. Client side files can only be accessed by the FileReader, specifying a user selected file.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function loadFile(o)
{
var fr = new FileReader();
fr.onload = function(e)
{
showDataFile(e, o);
};
fr.readAsText(o.files[0]);
}
function showDataFile(e, o)
{
document.getElementById("data").innerText = e.target.result;
}
</script>
</script>
</head>
<body>
Select file to read <input type="file" onchange="loadFile(this)">
<pre id="data"></pre>
</body>
</html>

As a general rule, it's not possible to access the local file system from JavaScript, so your code example shouldn't and couldn't work because of browser security.
However, there's the File and FileReader API which would allow you to read the contents of a file from an <input type="file" /> and is, in reality, your only option for this sort of thing - You could use FileReader.readAsText() to access the files contents. This is a good resource for further information:
https://www.html5rocks.com/en/tutorials/file/dndfiles/

The easiest way to solve my problem is to change the text file to a .js file, save it in the same folder and include it in the html file by <script src="test.js"></script>

Related

How to read local /proc files in JavaScript?

I have been trying to use FileReader to read out "/proc/cpuinfo" and print it on the webpage, but it gives nothing. I have tried both "readAsText()" and "readAsDataURL()" methods, which can read the files under a normal file system like ext3.
Can anyone share some insight on why it is like this? security reasons?
If I really want to read files under /proc in JavaScript, what should I do?
The following is my current code.
<html>
<head>
<script>
function readFile() {
var reader = new FileReader();
reader.onload = function(){
var show = document.getElementById('out');
show.innerText = reader.result;;
};
reader.readAsDataURL(document.getElementById("fileInput").files[0]);
};
</script>
</head>
<body>
<input type='file' id="fileInput" onchange='readFile();'><br>
<div id='out'>
</div>
</body>
</html>
EDIT: being asked to show code, well, it's really nothing but a simple file read. The problem here is how to read files in those pseudo FS like /proc and /sys in JavaScript. Try it yourself. You will see the problem.
KB

How to read local files using HTML 5 FileReader? [duplicate]

This question already has answers here:
Javascript read file without using input
(3 answers)
Closed 6 years ago.
Objective
I am making an application, and I need to read a local file using JavaScript and HTML 5, without any <input> tags or user interaction whatsoever.
What I tried
On my research, I found two tutorials that are heavily cited in SO:
https://www.html5rocks.com/en/tutorials/file/dndfiles/
http://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api
However, there is a problem. Both of this tutorials require user interaction via the input tag, which is a life killer since I want to read the contents of the file automatically into a string.
Code
So far I managed to get the following code:
let readFile = function(path) {
let reader = new FileReader();
reader.onload = function(e) {
var text = reader.result;
console.log(text);
};
// Read in the image file as a data URL.
reader.readAsText(MissingFileHandle);
};
But as you can see, I am missing an important step, I am missing MissingFileHandle. My idea would be to pass a path to this method, and so the method would read the file locally as text and print it into the console, but I am unable to achieve this.
Question
Given a relative path, how can I read the contents of a file using HTML 5 without using <input> tags?
The HTML5 fileReader facility does allow you to process local files, but these MUST be selected by the user, you cannot go rooting about the users disk looking for files.
Is it possible to load a file with JS/HTML5 FileReader on non served page?
How to open a local disk file with Javascript?
How to set a value to a file input in HTML?
Javascript read file without using input
These links help you to find answer.
This Can do a trick.
HTML
<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!"
}
});
}

Convert extension and open it using an application

I got a a script wherein I want to convert the extension to another one then open it using a specific application.
For instance, I got .mht file located in my Desktop. An html file with internal javascript on it.
What I want to happen is when I open the HTML file on internet explorer and click on the hyperlink, it should convert .mht file into .docx and open it using Microsoft Word. Unfortunately, my below code does not work, if i click the hyperlink, it does opens up Microsoft Word but giving me an error message saying that the file cannot be found. Can someone assist me with this please? Thanks in advance, will much appreciated.
<HTML>
<HEAD>
<script type="text/javascript">
<!--
function openDocument(file)
{
try
{
var Word = new ActiveXObject("Word.Application")
var file;
file = file.split(".");
file = file[0]+".docx";
Word.Visible = true
Word.Documents.Open(file)
}
catch(exception)
{
if(Word)
{
alert(exception.message)
Word.Quit()
}
window.location.href = file
}
}
// -->
</script>
<TITLE>Launch Word - Local</Title>
</HEAD>
<BODY>
Summary
</BODY>
</HTML>
For security purpose, Javascript can't write on the filesystem, so it is impossible to change the extension of a file.
You should be able to do something with the new FileSystem API (check that tutorial : http://www.html5rocks.com/en/tutorials/file/filesystem/), but it is available only on Chrome (http://caniuse.com/#feat=filesystem)
EDIT:
With an ActiveX, using GetFile may work:
var fso = new ActiveXObject("Scripting.FileSystemObject");
var file = fso.GetFile("c:\\myfile.mht");
file.name = "newName.newExt";

Access file from JS running localy

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/

reading and writing json file using javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to read and write into file using JavaScript
can anybody provide sample code to read and write into file using javascript?
at present i am trying to read input from json file and display it in textboxes providing the user flexibility to edit the data. Edited data has to be written into json file.
here is the sample html file, i have tested it with firefox working fine.
<!DOCTYPE html>
<html>
<head>
<script>
function handleFileSelect()
{
if (window.File && window.FileReader && window.FileList && window.Blob) {
} else {
alert('The File APIs are not fully supported in this browser.');
return;
}
input = document.getElementById('fileinput');
if (!input) {
alert("Um, couldn't find the fileinput element.");
}
else if (!input.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
alert("Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
fr = new FileReader();
fr.onload = receivedText;
fr.readAsText(file);
}
}
function receivedText() {
//result = fr.result;
document.getElementById('editor').appendChild(document.createTextNode(fr.result))
}
</script>
</head>
<body>
<input type="file" id="fileinput"/>
<input type='button' id='btnLoad' value='Load' onclick='handleFileSelect();'>
<div id="editor"></div>
</body>
</html>
JavaScript running in a web page displayed in a browser cannot access the client file system.
But you can use API's
(No File programming in javascript)
If you mean parsing json in javascript then :-
you can use Douglas crockford JSON lib for parsing:-
JSON.parse method
Refer Link :-
http://www.json.org/js.html
Example,
var abcd= "[{"name" : "sandeep"},{"name" :"Ramesh"}]"
abcd =JSON.parse(abcd);
for (var index=0;index<abcd.length;index++){
alert(abcd[i].name);
}

Categories