Read local text file using Javascript - javascript

I am following an old stackoverflow post on how to read in a text file using javascript seen here: Javascript - read local text file
and I cannot get it to work. I am very new to javascript and all I want to do is store the file to a var and display it on screen so I know it is being read in and split correctly. What am I doing wrong? I know there are many new ways to do this but this is a very early attempt at javascript for me and I found this code to be the most readable example I found online. Im not sure if it matters but the file im trying to read from is about 300 pages of gps data.
I tried:
pasting the file path into my browser (works fine)
removing the state and status checks (no difference.... and bad practice I know)
changing browsers (no difference, though I have been using Chrome)
var allText;
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)
{
allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
readTextFile("file:////var/www/html/gpsPoints.txt");
locations=allText.split(",");

Related

How to read a LOCAL binary file using JavaScript while in HTML

Currently I am building a local (non-internet) application that launches a Chromium browser in Visual Basic .NET.
It uses CefSharp to achieve this.
When the HTML launches I need to read multiple files in order to plot graphs using Plotly.
The problem: I can't read binary files.
I have succeeded in reading ASCII and non-binary files, by disabling security on CefSharp. I tried using the FolderSchemeHandlerFactory class, but that didn't work.
In order to read ASCII files I have resorted to using XMLHttpRequest which works for ASCII , but not binary. I have tried changing the response type to arraybuffer, but that doesn't work either.
function readTextFile(file){
var array = []
var file= new XMLHttpRequest();
file.open("GET", file, false);
file.onreadystatechange = function ()
{
if(file.readyState === 4)
{
if(file.status === 200 || file.status == 0)
{
var text= file.responseText;
array = text.split("\n");
}
}
}
file.send(null);
return array;
}

How do I include the contents of a text file into my website?

I am making my first blog, and I want to be able to write the posts as text files on a word processor like Microsoft Word so that I can spellcheck and check for mistakes, but then include the contents of those files into my website with custom formatting using CSS (e.g. add a style attribute to the HTML like this: style='font-family: sans-serif;').
I have already tried searching around the web, and I found this website blog.teamtreehouse.com, but it didn't suit my needs because it needs the user to click a button to include the file. I also came up with some test code that relies on the FileReader API, but since I don't understand the bits parameter of the File object (I left it blank), the test page just shows undefined. Here's the code:
<!DOCTYPE html>
<html>
<head>
<title>Test Webpage</title>
</head>
<body>
<p id='output'></p><!--p tag will have styles applied to it-->
</body>
<script>
var reader = new FileReader();
reader.onload = function(e) {
var text = reader.result;
}
//What does the first parameter do? What am I supposed to put here?
// |
// |
var file = new File([ ],'test.txt');
var txt = reader.readAsText(file);
var out = document.getElementById('output');
out.innerHTML = txt+'';
</script>
</html>
Just don't read files in js in a web browser.
You can create an API with node.js and then make an http request to get this data.
Once you created the server, just do like that:
const fs = require('fs');
var content;
// First I want to read the file
fs.readFile('./Index.html', function read(err, data) {
if (err) {
throw err;
}
content = data;
// Invoke the next step here however you like
console.log(content); // Put all of the code here (not the best solution)
processFile(); // Or put the next step in a function and invoke it
});
function processFile() {
console.log(content);
}
if you want to know how to do an api, here it is: https://dev.to/tailomateus/creating-an-express-api--7hc
Hope it helps you.
In case you have *.txt files on your server you can utilize Javascript to display the content in the browser like so:
fetch('/path/to/file.txt')
.then(r => r.text())
.then(txt => document.querySelector('<a selector>').innerHTML = txt);
That approach has the drawbacks:
The urls/filenames need to be known by the Javascript
Plain txt files do not contain any formatting, so the text block wont have a headline or alike.
But all in all: Without any server side processing this is a repetitive thing, since JS from the client side cannot even trigger a directory listing, to gain all the files that should be loaded, so for each new file you create, you have to add an entry in the Javascript as well. This is a very common problem an is already solved by the various content management systems out there (Wordpress, Joomla, Drupal,…), so I would recommend to just use on of those. Btw. Grav is a purely file based CMS, that works without a backend interface as well, so a very simple solution for your problem.
In the end, I used an HTTP request to retrieve the text from a file.
function includeText() {
var xmlhttp, allElements, element, file;
allElements = document.getElementsByTagName("*");
for (let i = 0; i < z.length; i++) {
element = allElements[i];
file = element.getAttribute("insert-text-from-file");
if (file) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {element.innerText = this.responseText;}
if (this.status == 404) {element.innerText = "Contents not found";}
elmnt.removeAttribute("insert-text-from-file");
includeText();
}
}
xmlhttp.open("GET", file, true);
xmlhttp.send();
return;
}
}
}

How would I convert a local image file to Base64 to POST to a custom API Endpoint?

I am working on a JavaScript library that is a rich text editor. Currently, we can not copy + paste from a Word Document due to the clipboard being a local file and most browsers block the ability to read local files. Our work around to this issue is to convert the local image file to a base-64, and using our local API, store the image on our servers so the img has a proper, hosted source.
The problem is this has to be handled entirely in JavaScript, which still is run in the browser and I can not see local files to be able to convert them:
This is currently the code I am trying to use, but can't seem to figure out a way to handle this entirely in JavaScript without using some time of File Loader from HTML.
function convertToBase64(){
var xhr = new XMLHttpRequest();
// Set up our request
xhr.open('POST', 'http://uploadFileHere');
//convert image to base64
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
//handle the response from Image API
xhr.onreadystatechange = function() {
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
return xhr.responseText;
}
}
xhr.send(base64String);
}
Is it possible to work around this issue or does my team and I have to come up with another solution?
EDIT: Here is another rich text editor, where it IS possible to copy and paste images from Word, Froala. If this is not possible, how are they doing it?

How to read a text file using JS code?

I am trying to read a file while using google charts. It first read he data from a text file and then create chart using that data.
I wrote this code in JS for this purpose
function readTextFile(file){
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false); // using synchronous call
var allText;
alert("Starting to read text");
rawFile.onreadystatechange = function ()
{
alert("I am here");
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
allText = rawFile.responseText;
}
}
}
rawFile.send(null);
alert(allText);
return allText;
}
The problem is : this method is getting called, but the control is not going in
rawFile.onreadystatechange = function ()
{ ... }
Do anyone have any idea regarding this?
Thanks in advance!
note: I am sending the file name in the parameter (file). I am not passing the address as both this HTML file and the text file are in the same folder.
update 1: I printed rawFile.readyState , and it always shows 1 which means server connection established. My code is a simple HTML code, not using any server for this purpose.
update 2: I tried adding file:/// before the file name that is not working too :(
I made the call asynchronous.
rawFile.open("GET", file, true);
Now it is working

Deleted file is still being accessed

I have a php script to delete an old instance of a csv file and upload a new one and a javascript function to read the file. It was working fine until I added the php to delete the old file, and now for some reason the javascript function always fetches the same file even when it's changed.
I've gone in and checked the data.csv file and it's the new file but the function still fetches the old one. And if I delete the file manually the function still mysteriously accesses the data.csv file... even though it's deleted.
This is the php:
<?php
if(file_exists('upload/data.csv'))
{
unlink('upload/data.csv'); // deletes file
}
$tmp_file_name = $_FILES['Filedata']['tmp_name'];
$ok = move_uploaded_file($tmp_file_name, 'upload/data.csv');
?>
This is the javascript. Note: the variable "allText" will always be the contents of the old CSV file even if data.csv has changed or is deleted.
function LoadCSV(){
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://****.com/mailer/upload/data.csv", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) { // Makes sure the document is ready to parse.
if (txtFile.status === 200) { // Makes sure it's found the file.
allText = txtFile.responseText;
ProcessCSV(allText);
}
}
}
txtFile.send(null);
}
I'm not sure why this is happening or how to fix it?
It's probably browser caching.
I like to use a random value in the url to trick the browser into thinking it is a different page:
Try this:
function LoadCSV() {
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://****.com/mailer/upload/data.csv?nocache="+(Math.random()+'').replace('.',''), true);
txtFile.onreadystatechange = function () {
if (txtFile.readyState === 4) { // Makes sure the document is ready to parse.
if (txtFile.status === 200) { // Makes sure it's found the file.
allText = txtFile.responseText;
ProcessCSV(allText);
}
}
}
txtFile.send(null);
}
The get parameter nochache doesn't mean anything to the server or browser, but fools it into fetching a new resource every time, at the cost of losing browser caching altogether. Technically it's possible(although spectacularly unlikely) to get the same value twice, so you can add time in milliseconds or something if you want to make it totally foolproof.
Note that this will also bypass almost all other types of caches as well.

Categories