Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read A Server Side File Using JavaScript

I have on my web server a JS script that I want to be able to read files. My filesystem is like this:

> Root
index.html
read.js
> files
    file.txt

In this example, the file "file.txt" will contain the simple word "Hello"

With JavaScript, I wish to be able to make a function, for example:

function read (path) {
    //Stuff to read the file with specified path
    var content = //whatever the content is
    return content;
}

And then be able to call it with:

var file = read("/files/file.txt")

And then when I do

alert(file)

It will pop up with/alert you with "Hello", the content of file.txt.

Is there any way that I would be able to do this?

like image 686
Gabriel Dunn Avatar asked Apr 28 '16 17:04

Gabriel Dunn


People also ask

Can JavaScript read server files?

You cannot read server side data through Javascript unless you have a connection to the server. Whatever Javascript code that runs on the client's browser will remain on their browser only, even if both are ran on the same computer.

Can you use JavaScript on server side?

JavaScript on the server-side (or outside of the browser) has opened a wide range of applications for the language. And that's one of the reasons it is one of the most popular right now. According to reports, JavaScript is being used on 97% of all websites. That's huge!

How do I read a text file on a server?

A text file on a server can be read with Javascript by downloading the file with Fetch / XHR and parsing the server response as text. Note that the file needs be on the same domain. If the file is on a different domain, then proper CORS response headers must be present.

How do you read a file in JavaScript?

To read a file, use FileReader , which enables you to read the content of a File object into memory. You can instruct FileReader to read a file as an array buffer, a data URL, or text. // Check if the file is an image.


2 Answers

Here's a sample web page for you:

http://sealevel.info/test_file_read.html

Here's the javascript code:

// Synchronously read a text file from the web server with Ajax
//
// The filePath is relative to the web page folder.
// Example:   myStuff = loadFile("Chuuk_data.txt");
//
// You can also pass a full URL, like http://sealevel.info/Chuuk1_data.json, but there
// might be Access-Control-Allow-Origin issues. I found it works okay in Firefox, Edge,
// or Opera, and works in IE 11 if the server is configured properly, but in Chrome it only
// works if the domains exactly match (and note that "xyz.com" & "www.xyz.com" don't match).
// Otherwise Chrome reports an error:
//
//   No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://sealevel.info' is therefore not allowed access.
//
// That happens even when "Access-Control-Allow-Origin *" is configured in .htaccess,
// and even though I verified the headers returned (you can use a header-checker site like
// http://www.webconfs.com/http-header-check.php to check it). I think it's a Chrome bug.
function loadFile(filePath) {
  var result = null;
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.open("GET", filePath, false);
  xmlhttp.send();
  if (xmlhttp.status==200) {
    result = xmlhttp.responseText;
  }
  return result;
}
like image 70
Dave Burton Avatar answered Sep 17 '22 13:09

Dave Burton


You want to be using XMLHttpRequest, like Gabriel has suggested.

You seriously need to read up on it, since it is very configurable and you need to understand the workflow in order to implement it. You will run into problems initially, if you are cross origin scripting.

Here is an example I mocked up for you:

<span id="placeholder"></span>
<script>
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            document.getElementById('placeholder').innerHTML = xhr.responseText;
        }
    }
    xhr.open('GET', 'test.html');
    xhr.send();
</script>
like image 22
Dan Schalow Avatar answered Sep 20 '22 13:09

Dan Schalow