How to get javascript file content in string form?

1

I'm doing a program that needs to read the source code of a javascript file. I was trying to get the javascript file via XMLHttpRequest and return this.responseText , however, its value is undefined . How do I return the contents of a javascript file in the form of a string (without jQuery or, preferably, without the use of third-party libraries)?

Follow the code below

function getScriptStr(filepath) {
    var http = new XMLHttpRequest();
    http.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
            return this.responseText.split('\n');
        }
    };
        http.open("GET", filepath, true);
        http.send();
};
    
asked by anonymous 07.03.2017 / 23:32

1 answer

3

When using XMLHttpRequest asynchronous you should use a callback function to return the response (if any) because return will always return undefined because it does not expect the "response" of the request .

Example:

´´´javascript

// instanciar a API
var XHR = ( new XMLHttpRequest() );

// função
var requestGet = function(url, callback){
    // catch response
    XHR.onreadystatechange = function(){
         if( XHR.readyState == 4 && XHR.status == 200 ){
             if( callback ){
                 callback(XHR.responseText);
             }
         }
    };
    // open
    XHR.open('GET', url, true);
    // check
    if( !url || typeof url !== 'string' || url.length < 2 ){
        return false;
    }else{
        // send
        XHR.send();
    }
};

// uso:
requestGet('https://code.jquery.com/jquery-3.1.1.min.js', function(res){
    if ( res !== false ) {
         console.log(res);
    }
});

If you want to use (import) strings in the format json you must use JSON.parse() to transform these strings into javascript objects again.

Example:

´´´json
{
     "a": "abacaxi",
     "b": "bola",
     "c": "carambola"
}

´´´javascript
// variavel pré-definida
var xmlhttpObj;

// no retorno do "callback"
if ( res !== false ) {
     xmlhttpObj = JSON.parse(res);
}

// posteriormente
console.log(xmlhttpObj.c); //output: carambola

If you'd like to learn more, API technical data, support, and other examples, it's worth checking the Mozila (sync | async) as well as Mozilla XMLHttpRequest

    
09.03.2017 / 01:04