Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a file in same directory as the JavaScript file

Tags:

I can load an image file located in the same relative path as the JavaScript file

var imgObj = new Image(); 
imgObj.src = "images/backdropLevel0.jpg";

But how do I do the same (as simply and with pure JavaScript) for a text file ?
(it has some initial data for a webGL game I am working on).

PS. I am not asking about user input from the client's computer using the new File object.

like image 714
Thomas An Avatar asked Jun 27 '17 01:06

Thomas An


People also ask

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.

Can I read text file using JavaScript?

The FileReader API can be used to read a file asynchronously in collaboration with JavaScript event handling.

Can JavaScript access local files?

Web browsers (and JavaScript) can only access local files with user permission. To standardize file access from the browser, the W3C published the HTML5 File API in 2014. It defines how to access and upload local files with file objects in web applications.


1 Answers

Fetching an image is easy since the browser takes care of all the fetching and rendering. However, loading an arbitrary file into your script requires a couple more lines:

var req = new XMLHttpRequest();
req.onload = function(){
    process_webgl_data(this.responseText);
};
req.open('GET', './webgl_init.dat');
req.send();

Where process_webgl_data is whatever you want to do with the text of the file.

EDIT: Two quick things. Remember that request URIs are resolved with respect to the html file rather than the script, and second, here's the documentation for XHR.

like image 110
wbadart Avatar answered Oct 11 '22 14:10

wbadart