Getting the data from a .txt file into a .js file - javascript

We need to extract information from a .txt file, into a .js file.
We've tried using 'Fetch API' but without luck, is there any other way to go about this.
We are using a Node.js Server to see what's going on
This is the contents of the .txt file
2min = 2:00
2min away = 2:00
ScoreAway = 7
ScoreHome = 8
Time = 30:00
halvleg = 2nd

Serverside use Node Js and Clientside use fs.
In a browser you can use XMLHttpRequest. Like this:
function readTxtFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "neuro.txt", false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
let allText = rawFile.responseText;
console.log(allText);
}
}
}
rawFile.send(null);
}
readTxtFile();

Related

Simply get each line in a .txt file into a javascript array

Thought this wouldn't be this difficult, but I'm simply trying to get the contents of a file and store each line into an array.
The 'file.txt' file (formatted as plain text):
file1.dwg
file2.dwg
file3.pdf
file4.dwg
file5.pdf
My javascript code:
function readTextFile('file.txt') {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", 'file.txt', false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
The syntax errors shown in the console:
- safari: SyntaxError: Unexpected string literal 'file.txt'. Expected a parameter pattern or a ')' in parameter list.
- chrome: Uncaught SyntaxError: Unexpected string
I'm running the files on a simple live server, with the following file structure:
- file.txt
- page.html
- script.js
The page.html just calls the script and is somewhere where I can work and open the console.
Why are the errors occurring, and how can they be fixed? I've tried to follow the instructions from this other post, but it has also failed: How to read a local text file?
Then I also tried the node solution and made my code like this:
var fs = require('fs');
var array = fs.readFileSync('file.txt').toString().split("\n");
for(i in array) {
console.log(array[i]);
}
I know nothing about Node but gave it a go - the errors were:
- chrome: Uncaught ReferenceError: require is not defined
- safari: ReferenceError: Can't find variable: require
Thanks for any help here - I don't know how to fix this seemingly simple problem.
function readTextFile(textFilePath) { //set a variable
var rawFile = new XMLHttpRequest();
rawFile.open("GET", textFilePath, false); //user variable here
let fileNameArray= [];//defined array here for now
rawFile.onreadystatechange = function (){
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
console.log(allText); //check in broswer console
//alert(allText)
//or enale the alert function
fileNameArray = allText.split('\n'); //split by line break and add to array
console.log(fileNameArray)
}
}
}
rawFile.send(null);
}
readTextFile('./text.txt'); // call function and pass relative path of text file here

Trying to post to a .txt file fails but performing a get does work

My partner and I are trying to get a domain that I own, communicate with a ios app that is run on objective c to work via http. He is using the code that was provided by this link Sending an HTTP POST request on iOS.
He is able to do a GET to receive the data in my .txt page but when he performs a PUT to try and write to that file so that I can get that data it fails. We are both rather new to http so it is possible that we are missing something. A concern we have is that he doesn't have the privileges to write to this file. Any advice would help, thanks!
Here is the javascript I am using on my side. I added a header to my response to try and resolve the cors issue.
(function () {
window.onload = function () {
httpGetAsync("http://students.washington.edu/bharatis/distances.txt", processData)
//alert("hello inside onload");
document.getElementById("first").innerHTML = leader1;
document.getElementById("second").innerHTML = leader1;
document.getElementById("third").innerHTML = leader1;
//window.onbeforeunload = update;
}
function processData(responseText) {
//alert(responseText);
var txt = "";
var x = responseText.getElementsByTagName('Distance'); // Talk to alex about
for(i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue;
}
var result = parseDouble(txt);
alert(result);
}
function httpGetAsync(theUrl, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xmlHttp.send("response message");
}
})();

How do I load a .txt file accessable by HTTP into a JavaScript array by lines?

I have a .txt file accessible by http (e.g. "http://foo.net/bar.txt", not actually a link). I'm trying to load it into a JavaScript array by lines using raw JavaScript, but no solution that anyone has posted seems to work. Or, rather, no solution that anyone's explained to the point where I can alter it effectively seems to work as I need it to.
Here's the two solutions I've found that, as explained, can be used with raw JavaScript.
var openFile = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function(){
var dataURL = reader.result;
var output = document.getElementById('output');
output.src = dataURL;
};
reader.readAsDataURL(input.files[0]);
};
and
function readTextFile(file){
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function () {
if(rawFile.readyState === 4) {
if(rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
Please note that neither of these solutions actually returns the text content of the text file, much less to an array with each cell of the array being an individual line of the text file. How can I accomplish this?
EDIT: Going with the second option, modified as follows:
function readTextFile(file){
var allText;
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function () {
if(rawFile.readyState === 4) {
if(rawFile.status === 200 || rawFile.status == 0) {
allText = rawFile.responseText.split("\n");
return allText;
}
}
}
rawFile.send(null);
}
...I get two errors.
Content Security Policy: Ignoring ‘x-frame-options’ because of ‘frame-ancestors’ directive.
and
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://foo.net/bar.txt. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Via the Debugger, I found that the program doesn't even step into the onreadystatechange part.
With your second example, you can convert it into an array by .splitting at \ns. allText.split("\n") will return an array of all the text seperated by newlines.
Your second example will only work if the address is on the same website the page is on or if it can get through CORS. This is for security because otherwise if you were signed into a page, another website could make you post things or do actions without your visiting that site.
To enable CORS for your site so you can access the text file, you can set the Access-Control-Allow-Origin header to * in the response.

Reading CSV file in to an array using javascript

I'm trying to do something fairly simple I think but I'm missing something. I've very new to Javascript. I'm trying to read a CSV file in to an array (in my code below I'm simply trying to output the data to an alert box). I keep getting an error "access denied."
function readTextFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function () {
if(rawFile.readyState === 4) {
if(rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
I suspect there is an issue with where I have the csv file located? Due to restrictions with our CMS I can only reference the file like this www.example.com/csvfile.csv.
Any help would be greatly appreciated.
Here is sample code for reading csv file into array
var request = new XMLHttpRequest();
request.open("GET", url, false);
request.send(null);
var csvData = new Array();
var jsonObject = request.responseText.split(/\r?\n|\r/);
for (var i = 0; i < jsonObject.length; i++) {
csvData.push(jsonObject[i].split(','));
}
// Retrived data from csv file content
console.log(csvData);
Here is the working fiddle example: http://jsfiddle.net/BdCnm/450/
Give this link a try and check his source code on Github, he lays it out in a pretty concise way.
https://github.com/MounirMesselmeni/html-fileapi

Only getting first line of file when loading into JavaScript because transfer-encoding: chunked

I have a file that looks like this
1 4
2 4
3 6
I load it into my code like this
var file = 'fileName';
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function () {
if(rawFile.readyState === 4) {
if(rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
console.log(allText);
setTimeout(otherFunction, 3000);
}
}
}
rawFile.send(null);
When I do
console.log(allText);
This is output:
1 4
//blank line
Why, and how do I fix it?
Edit: I see in the network tab that the downloaded file looks just like the console.log() output. However the file on the server looks as described at the top of this Question.
Edit: The problem is that
transfer-encoding: chunked
I need to either "unset transfer-encoding" or set the length of the file. But where and how do I do this? There is no PHP-file, the file is loaded directly from my server to JavaScript.
OP sais: Chucked without length in chat.
So i referee
http://en.wikipedia.org/wiki/Chunked_transfer_encoding
"The size of each chunk is sent right before the chunk itself so that the receiver can tell when it has finished receiving data for that chunk. "

Categories

Resources