How to get javascript file content in string form?

Asked

Viewed 893 times

1

I am making 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 the this.responseText, however, its value is undefined.
How do I return the content of a javascript file in string form (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();
};
  • Rename the file you want to import from ". js" to ". txt"

  • @inovapixel can not, the goal is exactly it read javascript files

  • Xmlhttprequest does not execute the code... The code returned is a text/json, text/Plain or other MIME. You cannot simply include your file in the HTML document?

  • You shouldn’t have much trouble doing that, but to a limitation. If the JS file is not on your server you may not have access to make this request. Anyway, put your code here so we can help. Hug

  • @inovapixel I know it doesn’t run, however I don’t understand why it returns Undefined if the file is found

  • 1

    Because Xmlhttprequest returns plain text, not the file itself. If you could return ". js", would be only the text that is contained in it, so it makes it either ". txt" or ". js"

  • @inovapixel yes, but for me is returning Undefined.

  • Dude, but whatever, it won’t do you any good to get the ". js". I think it returns "Undefined" for ". js" files not being accepted by XHR. I’m not sure, but I don’t think they’re accepted, no.

  • @Gabrielc. here on the site we do not put the question as answered, you either mark an answer as correct or answer your own question and mark as correct.

  • @inovapixel All right, I’ve solved the problem =)

  • @Jorgeb. sorry, I’m new to the site. I think I’ll answer my own question then.

  • @Gabrielc. in the good, nobody born taught. And welcome to the site :)

  • 1

    @inovapixel XHR accepts js files

  • 1

    @Denisrudneidesouza I got it. As I said, I wasn’t sure, it was just a hunch for returning the "Undefined".

  • 1

    Also not sure, I did some tests here to confirm, the only mistake I had was CORS, but otherwise I managed to get any content by XHR

Show 10 more comments

1 answer

4


When using XMLHttpRequest asynchronous you should use a function of callback to return the answer (if any) because Return always returns undefined because he doesn’t expect "the answer" to 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 format json you must use JSON.parse() to transform these strings on objects javascript 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 want to know more, technical API data, support and other examples are worth taking a look at Mozila (Sync|async) as well as Mozila Xmlhttprequest

  • Great answer, this explains why the Return was not working properly, given that the variable needed an immediate return of the function, and as this was asynchronous, could not immediately return the necessary value, this clarified a lot, thank you. This way I replace the Return with the value assignment and put the following steps together with the callback function.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.