Parsing an existing text file with no user selection - javascript

Long story short, I am looking to parse a text file (eventually kept on a server, but for now tested locally) that will update content, but will never change file location, name or extension.
Let's say the file is called feed.txt in C:\files. So, I always want my parser to traverse through the static C:\files\feed.html.
I know am all familiar with
<input type="file" name="file" id="file">
for user selection, but I want my javascipt parser to skip that all together, grab the file, parse it as such:
document.getElementById('file').onchange = function(){
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent){
// Entire file
console.log(this.result);
// By lines
var lines = this.result.split('\n');
for(var line = 0; line < lines.length; line++){
console.log(lines[line]);
}
};
reader.readAsText(file);
};
and have certain strings being displayed back into my html (code not written yet - still on the parsing part). How do I go about skipping user file selection and just having the javascript know which file (and where) to parse?
Thanks!

Related

Using JavaScript to load data from CSV file into the script as array

I am working on an Adobe Illustrator JavaScript and need to load data from a CSV file on my computer as an array into the script so I can work with them later (everything Is happening on my computer, and nothing happens online/web browser.) I need every line of the text in the CSV to be separated in the array, and then I need to separate the words in the line into an array so that I have an array of arrays in the end. Each line has three variables which get fed into a function that has to happen for each line.
The error I am getting from the code below says:
'Error 25: Expected: ;. -> let reader = new FileReader();'
var csv = Folder ("Path to my csv file");
function processData(csvFile) {
let reader = new FileReader();
reader.readAsText(csvFile);
reader.onload = function(event) {
var allText = reader.result;
};
const allTextLinesArr = allText.toString().split(/\r\n|\n/);
var alen = allTextLinesArr.length;
const allTextLinesArrArr = [];
for (var i=1; i<=alen; i++) {
allTextLinesArrArr[i-1] = allTextLinesArr[i-1].split(",");
}
for (var i=1; i<=alen; i++) {
doStuff(allTextLinesArrArr[i-1][0],allTextLinesArrArr[i-1][1],allTextLinesArrArr[i-1][2]);
}
}
Here is the classic native Extendscript way to read CSV data from a file:
var csv_file = File('test.csv');
csv_file.open('r');
csv_file.encoding = 'utf-8';
var data = csv_file.read().split('/\r\n|\n/'); // split by lines
csv_file.close();
for (var row in data) data[row].split(','); // split all lines by comas
alert(data); // here is your 2d array
Error 25 isn't a standard Javascript error that you'd ever see in a web browser.
Are you using something like Adobe ExtendScript perhaps? If so, perhaps update your question with exactly where this code is being used.
The answer however, is probably that the program that you're using has an old version of Javascript that doesn't support FileReader (which is a fairly new bit of Javascript code).
It's also worth noting that you wouldn't usually be able to access the user's file from Javascript (without the user selecting it manually). However, it's possible that the program you're using to run JS does support this.

in js, why is my filereader unable to track my inputfile when I edited it

Maybe naive question but I'm wondering this:
I have an html input allowing me to find a local file on my computer. <input type="file" id="importFile">
From this input, i create a FileReader in js to display the text file content on my page
var search_file = document.getElementById("search_file")
search_file.addEventListener('change', function(){
var reader = new FileReader();
var tmp = [];
reader.readAsText(file_to_survey);
reader.onload = function(e) {
var contents = e.target.result;
//function to edit html thanks to content//
}, false);
This part is actually working well BUT if I edit or replace the file I targeted (with exact same file name), I'm not able to display the file without to search it again with the html input mentionned above.
Is there a way to keep trace of my file even after edition?
Many thanks for your help. I dug quiet a lot to solve my problem but maybe I'm thinking the wrong way. Any clue would be nice.
Because that's how the input type=file element works, and to my best knowledge there is no way for you to force the browser to automatically re-read a file from the user's hard drive without their express consent.
You can put the change handler of the file input in a separate function, and call that function when needed.
function loadFile () {
var reader = new FileReader();
reader.addEventListener('load', function () {
file = reader.result;
// Handle the changes here
console.log(file);
});
reader.readAsText(fileField.files[0]);
}
const fileField = document.getElementById('load'),
reloadBut = document.getElementById('reload');
let file;
reloadBut.addEventListener('click', loadFile);
fileField.addEventListener('change', loadFile);
<input type="file" id="load">
<button id="reload">Load</button>
A separate button is used to reload the file in this snippet, but you can call loadFile where ever you need, ex. in an interval or from some event handler knowing the file was changed etc.
Note: This works in Chrome only, other browsers seem to lose the reference to the file browsed into file input when the file is changed. Also, the file must be properly closed after saving, before reloading.

Loading and Reading text file onto HTML/JavaScript

I am trying to read and load a locally stored text file (it's saved on the user's computer, but may be moved to a local directory) into a variable or array so that I can generate a table with it in HTML.
I have found a way to have the user select and upload the file, but the code displays the text on the browser. I want it stored so I can manipulate the data so that I can put it in the correct row and cell. I know how to create a table, format it, format and splice text and things similar to that.
The code, which I found here but forgot which specific ask it was, goes as follows
<div id="page-wrapper">
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
<script>
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!"
}
});
}
</script>
For reference, here's a sample of the text file and here's what I want.
I am still relatively new to HTML and Javascript, but eager to learn. Anything will be appreciated.
You already have some parts working:
You have found a way to have the user select and upload the file
You know how to create a table, format it, format and splice text and things
Now we need to connect these things. Unfortunately, now all the script does is display the text on the browser when the user loads a text file. This is the part of the code responsible for that:
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
It displays it inside the <pre id="fileDisplayArea"><pre> area of your html. You want to store it inside a variable, so you can start to create a table, format it, format and splice text and things (the part 2 you already know):
reader.onload = function(e) {
myTextToFormat = reader.result;
// start formatting and make it into a table...
}

Javascript load/read text file by clicking a button

I want to use a button, instead of this input box to load the text file. When I press the button, I want to load a text file called "me.txt" without showing a browse window. ("me.txt" is in the same path). Is there anyway to do that?
<input type="file" name="file" id="file">
<script>
document.getElementById('file').onchange = function(){
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent){
var lines = this.result.split('\n');
for(var line = 0; line < lines.length; line++){
var wordStr = (lines[line]);
var index = wordStr.indexOf("="); // Gets the first index where a space occours
var word = wordStr.substr(0, index); // Gets the first part
var meaning = wordStr.substr(index + 1);
if (word=="a") {
document.write(meaning);
}
}
};
reader.readAsText(file);
};
</script>
You cannot read a file from the user's computer without the user actively picking the file; and you cannot know the real path of that file on the user's computer. Browsers quite rightly prevent both of those things.
When I press the button, I want to load a text file called "me.txt" without showing a browse window. ("me.txt" is in the same path).
If you mean that me.txt is a file that's on the same path as the HTML page this code is running in, then:
If you're using a web server process and accessing the page via http:// or https://, you can use a simple ajax request to read the file, for instance:
$.get("me.txt").then(function(data) {
// ...use data...
});
If you're just running from the local file system (a file:/// URL), it's much better to use a local web server process instead. But if you have to use a file:/// URL, you can't read other local files in Chrome, but you can in Firefox:
// NOT allowed from file:/// URLs not work in Chrome; is allowed in Firefox
$.ajax({
url: "test.json",
dataType: "text"
}).then(function(data) {
// ...use data here
});
Firefox will report an XML parsing error in the console, but will also give you the data.

How to read the first line of .txt file?

can anyone one help how to read the first line of .txt file? I have input type file that upload example.txt then I would like to grab the first line from that code. I tried something like this:
<input type="file" id="fileUpload" name="fileUpload"/> MyTest.txt //file name
function confirmFileSubmit(){
var fileName = $('#fileUpload').val();
alert($('#fileUpload').split('\n')[0]);
}
After I run my code this just outputted file name in alert box. I'm not sure how I can read the content of the file. If anyone can help please let me know.
You'll need the FileReader for that
function confirmFileSubmit(){
var input = document.getElementById('fileUpload'); // get the input
var file = input.files[0]; // assuming single file, no multiple
var reader = new FileReader();
reader.onload = function(e) {
var text = reader.result; // the entire file
var firstLine = text.split('\n').shift(); // first line
console.log(firstLine); // use the console for debugging
}
reader.readAsText(file, 'UTF-8'); // or whatever encoding you're using
// UTF-8 is default, so this argument
} // is not really needed

Categories