Squiller Squiller - 2 months ago 6
Javascript Question

What's the easiest way to link a file to a Javascript program?

I'm currently making a little offline html tool and I need to use a loooong list of objets that I have stored in an array but that would be way too big to store in my original javascript file.

My question is : how can I store this in a file, like, "DB.txt" that I can then reuse in my javascript program ?

EDIT : seems like I'm stupid and that the "easiest" way for me to do this was just to create another javascript file where I just create an array with all my values. Thanks everybody !

Answer

If you want to avoid the use of a small DB like indexedDB (as suggested by A.Wolff), you can create a text file and then access it through ajax:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'path/to/your/text/file', false);
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == '200') {
        // the responseText property is the content of the file
        // then you can do whatever you want with the file
        console.log('file', xhr.responseText);
    }
};
xhr.send(null);

You can also put this code in a function with a callback:

function loadAjax(file, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', file, false);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == '200') {
          callback(xhr.responseText);
        }
    };
    xhr.send(null);
}

And then call it:

loadAjax('path/to/your/text/file', function(response) {
    console.log('file', response); // content of file
});

Or use a more modern solution (fetch, but with a polyfill with old browsers) or an external library (jQuery, superuser,...).

You could, in addition, store your data in a json file, and while still fetching it through ajax, parse it easily. For instance:

loadAjax('path/to/your/json/file', function(response) {
    console.log('file', JSON.parse(response)); // content of file
});