Geting content from txt file with javascript - javascript

I am a quite coding beginner and I am struggling a lot to get data from a .txt with Javascript. I have a really simple txt file.
I would like to read the file with Javascript and store the info ideally into an array.
Here is my txt content:
"Italy": 30,
"France": 28,
"Netherlands": 1,
"Germany": 14,
"Greece": 4,
"Spain": 3,
"others": 12
What I manage to do after checking all the posible forums is the following. I can select the txt file and display the content with this following code:
HTML:
<!DOCTYPE html>
<html>
<style type="text/css">
#filecontents {
border:double;
overflow-y:scroll;
height:400px;
}
</style>
<head>
<meta charset="UTF-8">
<script src="FileReaderLogic.js"></script>
</head>
<body>
Please Select text file of which contents are to be read:
<input type="file" id="txtfiletoread" />
<div>The File Contents are as below:</div>
<div id="filecontents">
<script>ReadText()</script>
</div>
</body>
</html>
FileReaderLogic.js:
window.onload = function ReadText() {
//Check the support for the File API support
if (window.File && window.FileReader && window.FileList && window.Blob) {
var fileSelected = document.getElementById('txtfiletoread');
fileSelected.addEventListener('change', function (e) {
//Set the extension for the file
var fileExtension = /text.*/;
//Get the file object
var fileTobeRead = fileSelected.files[0];
//Check of the extension match
if (fileTobeRead.type.match(fileExtension)) {
//Initialize the FileReader object to read the 2file
var fileReader = new FileReader();
fileReader.onload = function (e) {
var fileContents = document.getElementById('filecontents');
fileContents.innerText = fileReader.result;
}
fileReader.readAsText(fileTobeRead);
}
else {
alert("Please select text file");
}
}, false);}
else {
alert("Files are not supported");
}
}
This works fine but I do not manage to change this code in oder to enter directly inthe code the file name/path (no button and no selection from the user needed) and store the file data into a variable or an array.
Could you please help me?
thanks a lot

This can be accomplished much simpler with an AJAX (Asynchronous JavaScript and XML) call for the text file's contents and then modify the text file just a little bit so that the data is stored in JSON (JavaScript Object Notation) format.
You can hard-code the path to the text file into the configuration of the AJAX component.
Also, your data in the text file is more suited to a JavaScript Object, rather than an Array because arrays don't allow for setting up key/value pairs without getting into nested arrays. Objects are data structures that store key/value pairs and, as a matter of fact, if you simple wrap your text file's contents with { and }, you will have the syntax for an object converted to JSON format.
data.txt (This is a string that conforms to the JSON data format)
{
"Italy": 30,
"France": 28,
"Netherlands": 1,
"Germany": 14,
"Greece": 4,
"Spain": 3,
"others": 12
}
HTML (Note: your tag was not located properly)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="FileReaderLogic.js"></script>
<style>
#filecontents {
border:double;
overflow-y:scroll;
height:400px;
}
</style>
</head>
<body>
Please Select text file of which contents are to be read:
<div>The File Contents are as below:</div>
<div id="filecontents"></div>
<script>ReadText()</script>
</body>
</html>
FileReaderLogic.js
var dataObj = null; // Will hold data after AJAX call completes
function ReadText() {
// Create instance of XHR
var xhr = new XMLHttpRequest();
// Set up event callback functions
xhr.addEventListener("load", transferComplete);
xhr.addEventListener("error", transferFailed);
// Configure the request. Replace pathToTextFile with a relative
// path to a file (in the same domain as this file).
xhr.open("GET", pathToTextFile, true);
// Request body will be plain text
xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
// Make the request:
xhr.send(null);
}
// Success Callback:
function transferComplete(evt) {
// Place the response in the HTML placeholder:
document.getElementById("filecontents").textContent = xhr.responseText;
// Turn text file content into object
dataObj = JSON.parse(xhr.responseText);
// Now, use the object as you like:
console.log(dataObj.Italy); // 30
// This will print all the key/value pairs
for(var key in dataObj){
console.log(key + " = " + dataObj[key]);
}
}
// Error callback:
function transferFailed(evt) {
console.log("An error occurred while processing the request.");
}

As said in the comments, you can't for obvious security reasons.
Now, this kind of question often come from a wrong point of view on what problem you have and how to solve it.
Quickest way from where you are to make it work, if I understand your needs (it's a big if ^^) :
1-rename your .txt file as .js
2-make its content a js Object like so :
var country_code={
"Italy": 30,
"France": 28,
"Netherlands": 1,
"Germany": 14,
"Greece": 4,
"Spain": 3,
"others": 12
};
3-include your js file in your html
<script src="./script/country.js" type="text/javascript"></script>
And there you have your array variable with all your values from your file, usable in your main page.
For example :
<script type="text/javascript">
var test='';
for (var country in country_code) {
test += country+':'+country_code[country]+'<br />';
}
document.body.innerHTML = test;
</script>
Does it help ?

Related

Read JSON from from HTML file input

If I have an input:
<input type="file" id="upload" onchange="getFile(this)">
And my user will upload a JSON file (as plaintext, so I will have to use JSON.parse()), how can I take this file and actually get the data via getFile()
In getFile(element), I've tried using element.files[0] but that doesn't seem to contain the actual data. I've also looked here, here, and here, but none of these solve my problem. This resource on MDN seems promising, but I don't really get it.
I would like a solution involving either URL.createObjectURL() or FileReader().
Also, before anyone posts this in the comments, I do understand that these solutions do not work on all browsers, and I would like to do this from the frontend.
You could take advantage of the Response constructor and call .json() on any blob/file.
function getFile (elm) {
new Response(elm.files[0]).json().then(json => {
console.log(json)
}, err => {
// not json
})
}
Alternative method using the new read methods on blob.prototype[...]
new Blob(['1']).text().then(JSON.parse).then(console.log)
I guess for larger files response.json might be faster/better since it can parse the content in background and not block the main UI unlike JSON.parse
I think you need this api:
FileReader Api From MDN
JSON#parse()
View In Stackblitz
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Read Text</title>
<style>
div {
margin-top: 30px;
border: solid 1px black;
padding: 5px;
}
</style>
<script>
function processFiles(files) {
var file = files[0];
var message = document.getElementById("message");
message.innerHTML = "File Name:" + file.name + "<br>";
message.innerHTML += "File Size:" + file.size + "<br>";
message.innerHTML += "File Type:" + file.type + "<br>";
var reader = new FileReader();
reader.onload = function (e) {
var output = document.getElementById("fileOutput");
// parse string to json
output.textContent = JSON.parse(e.target.result);
};
reader.readAsText(file);
}
</script>
</head>
<body>
<input id="fileInput" type="file" size="50" onchange="processFiles(this.files)">
<div id="message"></div>
<div id="fileOutput"></div>
</body>
</html>

Automatically load csv/txt file from local drive into html page as table Javascript

I found a lot of good suggestions on how to load a csv/txt file into a html page into a table, but none of the solutions are working for me. Here is the code I am working with. I have both files located in my C: drive and basically would like to load this csv/txt file and show it on as a table in index.html. Thanks so much!
data.txt
heading1,heading2,heading3,heading4,heading5
value1_1,value2_1,value3_1,value4_1,value5_1
value1_2,value2_2,value3_2,value4_2,value5_2
index.html
<!DOCTYPE html>
<!-- saved from url=(0014)about:internet -->
<html lang="en">
<html>
<head>
<title>Test</title>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "GET",
url: "data.txt",
dataType: "text",
success: function(data) {processData(data);}
});
});
function processData(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
var lines = [];
for (var i=1; i<allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j=0; j<headers.length; j++) {
tarr.push(headers[j]+":"+data[j]);
}
lines.push(tarr);
}
}
\\ alert(lines);
}
</script>
</body>
</html>
You can't access local files with JS. That would be serious security vulnerability, because you could send a malicious webpage to a user, which would download their files and send them to someone. As midrizi mentioned in the comments, you'll need a server to download files from there.
As others have noted, you can't automatically read a local file into the browser.
But you can prompt the user to select a file, using the <input type="file"> element.
Once a file has been selected via that input, it can be read via JavaScript.
<label for="file">Select a Text File:</label><br />
<input id="file" type="file" /><br/>
<button onclick="readFile()">Read File</button><br/>
let input = document.getElementById('file');
let contents = document.getElementById('contents');
function readFile () {
let file = input.files[0];
const reader = new FileReader();
reader.onload = function (evt) {
console.log('reader.onload');
contents.innerHTML = String(evt.target.result);
};
reader.readAsText(file);
}
If you can modify the data.txt a bit you can just load it as another script file without need for a server.
Change data.txt to this
var data = `heading1,heading2,heading3,heading4,heading5
value1_1,value2_1,value3_1,value4_1,value5_1
value1_2,value2_2,value3_2,value4_2,value5_2`
And load it as a javascript file before your actual script
<script type="text/javascript" src="data.txt"></script>
Then you can use the variable data which holds your file content without any ajax call.
There is no way you can retrieve a local file if you don't serve it, as pointed out in the comments to your question.
There are approaches you can take to that, though. If you can't serve it by any means, you could create a GitHub repo and upload your file there. Then you can use the link to your raw file:
And you can also take steps to automate that, but it should be easy enough committing your file locally whenever you update it and push it to GitHub. Just in case you're not familiar with Git and GitHub, here's a handy ref.
A word of caution: unless you have total control over the characters that you include in your CSV, parsing them by naively splitting commas like that might result in ugly stuff if the values within contain commas themselves. Some CSV files also come with extra stuff in the beginning of the file (like the sep indicator in the first row, which defines what character to interpret as separator). You may completely ignore these warnings if you're producing the CSV yourself.
Also I noticed your function does not take care of building the actual table, so I changed it so it does. I also used Fetch API to retrieve the data:
<!DOCTYPE html>
<!-- saved from url=(0014)about:internet -->
<html lang="en">
<html>
<head>
<title>Test</title>
</head>
<body>
<script type="text/javascript">
function processData(csv) {
let data = csv.split(/\r\n|\n/).map(v => v.split(','));
let headers = data.shift();
let table = document.createElement('table');
let thead = document.createElement('thead');
table.appendChild(thead);
thead.innerHTML = '<tr><th>' + headers.join('</th><th>') + '</th></tr>';
let tbody = document.createElement('tbody');
table.appendChild(tbody);
for (let row of data) {
tbody.innerHTML += '<tr><td>' + row.join('</td><td>') + '</td></tr>';
}
document.body.appendChild(table);
}
// I uploaded the CSV to a personal repo for this example,
// but you CAN use a local file as long as you *serve* it
fetch("https://raw.githubusercontent.com/gyohza/test/master/so/data.txt")
.then(res => res.text())
.then(text => processData(text));
</script>
</body>
</html>

Getting text from file using FileReader on Load

So, I've been working on a page that uses only local files (server is not an option, unfortunately. Not even a localhost. The struggle is real.) and I've come to a situation where I need to grab text from a .csv file and populate it to the page. I have this bit of code that works, but I need to have a file set within the function when a button is pressed. Looking up the file manually isn't an option (to visualize what I'm doing, I'm making a mock database file in the most annoying way possible (because I have to, not because I want to)).
In the page I would have something like:
<button id="myButton" onclick="getText()"></button>
<script>
var myFile = "dataset.csv";
...
</script>
The following bit of code works (in regards to having it pull the data from the csv file), but, as I said, I need to pull the text from the file when a button is pressed and just have the file name set in the script, not pulling it up manually.
<!DOCTYPE html>
<html>
<body>
<input type="file" id="fileinput" />
<div id="outputdiv"></div>
<script type="text/javascript">
function readSingleFile(evt) {
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
var splited = contents.split(/\r\n|\n|\r|,/g);
for (i=0; i<splited.length; i++){
document.getElementById("outputdiv").innerHTML = document.getElementById("outputdiv").innerHTML + splited[i] + "<br>";
}
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>
</body>
</html>
From what I can tell from the API, I would need to set the file attributes to a blob in order to pass it to FileReader. How I can do this without using an input box, I have no idea. There's also a 50% chance that I am completely wrong about this since I obviously don't know how to get this done.
If someone could show me how to achieve this with regards to what I'm looking for, it would be very much appreciated. I'm absolutely stumped.
Thank you.
Note: CORS restrictons will prevent this from working in most browsers. You can use FireFox Developer Edition, which disables CORS validation.
You can use an XMLHttpRequest to load a local file:
<!DOCTYPE html>
<html>
<body>
<button onclick="readSingleFile()">Click Me</button>
<div id="outputdiv"></div>
<script type="text/javascript">
function readSingleFile() {
let xhr = new XMLHttpRequest();
let url = "relative/path/to/file.txt;
if (!url) return;
xhr.onload = dataLoaded;
xhr.onerror = _ => "There was an error loading the file.";
xhr.overrideMimeType("text/plain");
xhr.open("GET",url);
xhr.send();
}
function dataLoaded(e){
var contents = e.target.responseText;
var splited = contents.split(/\r\n|\n|\r|,/g);
for (i=0; i<splited.length; i++){
document.getElementById("outputdiv").innerHTML = document.getElementById("outputdiv").innerHTML + splited[i] + "<br>";
}
</script>
</body>
</html>

Javascript/Jquery JSON File Upload

I have to create a html list with one li name import . On back i have create input type ="file" which will be hidden .
If user click on import it should fire file upload from back using .click()[![enter image description here][1]][1].
Once the use select the .json file it can be of any name ..
Then On click of open button of file upload it should save the json and pass the json object with an event dispatcher . I have create event dispatcher but not able to get json
Issue : I am not able to save the json object using .onChange and also .onChange work single time then i have to refresh then it work again.
Requirement: On click of import button, hidden file import will fire then on selecting the json file of any name (json filem can be of any name) function will save the json object and json object will be sent using iframe using event dispatcher .
Issue:: Not able to save the json or get the json . I tried getjson but it if for single file name .
<!DOCTYPE html>
<html>
<meta charset="UTF-8"/>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('button').click(function (){
$('#import').click();
});
$('#import').on('change',function () {
// not able to get json in a json object on selection of json file
var getJson = $('#import')[0].files;
// dispatcher just take json object and it will send to iframe .
// WindowDispatcher("Send Json", getJson);
});
});
</script>
</head>
<body>
<input type='file' id='import' style = "display:none" accept='.json ' aria-hidden="true" >
<ul>
<li>
<button id="importLink" >import</button>
</li>
</ul>
</body>
</html>
$(document).ready(function(){
$("#importLink").click(function(){
$("#import").click();
});
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
$("#import").on('change',function(e){
var file = e. target. files[0];
var path = (window.URL || window.webkitURL).createObjectURL(file);
readTextFile(path, function(text){
var data = JSON.parse(text);
console.log(data);
//Your ajax call here.
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="file" id="import" style="display:none" accept='.json' aria-hidden="true" >
<ul>
<li id="importLink">import</li>
</ul>
<output id="list"></output>
<div id="name">list</div>
<div id="age">list</div>
Read file from e. target. files[0];
Off what I can see, you are missing an argument list for your import onChange listener.
In the first image, you are calling $'#import').click() -- you are missing the leading (
you should be getting a javascript error when running the code you mentioned, since you don't include at least an empty argument list when the file input changes, though I could be wrong.

Show excel data in html without any server

I have an XLS file with data in it.
The excel file has a lot of reference in one column, so I want the user to type the reference then the web page search for the reference and show the data in the line found.
I can't use a server, so I want to do it without PHP or things like that.
Is it possible ? How can I do that ?
Thanks
Here is the sample of js-xlsx, and will return all values in all worksheets as JSON object, you may need to modify by your usage.
<html>
<script src="xlsx.core.min.js"></script>
<head></head>
<body>
</body>
<script type ="text/javascript">
"use strict";
var X = XLSX;
function convertFile(b64data) {
var wb = X.read(b64data, {type: 'base64',WTF: false});
var result = {};
wb.SheetNames.forEach(function(sheetName) {
var roa = X.utils.sheet_to_row_object_array(wb.Sheets[sheetName]);
if(roa.length > 0){
result[sheetName] = roa;
}
});
return JSON.stringify(result, 2, 2);
}
</script>
</html>
More option (by upload file, drag and drop option), you can study the source code of js-xlsx example: http://oss.sheetjs.com/js-xlsx/
You don't need PHP but at least Javascript.
You can do it like this:
var excel = new ActiveXObject("Excel.Application");
var wb = excel.Workbooks.Open("Path/to/your/excel/file.xls");
var ws = wb.ActiveSheet;
var cell = ws.Cells.Find("your search input");
alert(cell.Row);
excel.Quit();
I hope i could help you;)

Categories