30

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?

5 Answers 5

37

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Any suggestion on what to do about the warning this causes? "[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check xhr.spec.whatwg.org." How would one move this to a worker thread?
Don't worry about it. It slows loading no more than any other synchronously loaded page element, like img tags.
4

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>

3 Comments

Would I be able to set a variable to the content the same way that I would be able to set the innterHTML of #placeholder?
Yes, attach it to the window object. window.myVar = xhr.responseText
This is assuming the file 'file.txt' is actually being served by something. There's no way to access the file by XHR if it's not even being opened up to the 'outside world'
3

What you're looking for is XMLHttpRequest.

2 Comments

Would you be able to tell/show me how to use XMLHttpRequest to achieve this?
Literally the first code example on developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/… is almost exactly what you're asking for. Just replace the URL with yours.
3

This is a very simple task if you are using JQuery - The below example will perform an HTTP GET request (using XMLHttpRequest.as referenced above) and will put the contents into an HTML DOM object with the ID of "result". It will also throw an alert box up once the load is completed.

$( "#result" ).load( "files/file.txt", function() {
  alert( "Load was performed." );
});

Comments

1

It's not as simple as it sounds and you are going to have to do some research on server vs client.

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. What you need is a way to make the client (in this case, the html+javascript website) communicate with the server.

There are endless ways to do this but the most simple is through a GET request to a server that is serving that text file.

Try looking into serving static files with NGINX or maybe something like NodeJS, depending on what meets your needs. From there, create a GET endpoint that your Javascript is going to connect to through an XMLHttpRequest (like @MattW. said).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.