1

I am currently using Node.js to handle the back-end of my website but I am unsure of how Websockets/Objects are handled together.

This is a template I am using as an example of my main class. (Sends web-requests to a specific page)

class ViewClass {
constructor(URL, views) {
    this.link = URL;
    this.views = views;
    this.make_requests();
}

make_requests() {
    try {
        const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
        const xhr = new XMLHttpRequest();

        let link = this.link;
        let views = this.views;

        for (let index = 1; index < views + 1; index++) {
            xhr.open("GET", link, false);

            xhr.onload = function (e) {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        console.log("View: " + index + " Sent Successfully!");
                    } else {
                        console.error("View: " + index + " Failed!");
                    }
                }
            };

            xhr.send(null);
        }
    } catch (error) {
        console.log(error.message);
    }
}

}

This is my Main Websocket File (Stripped for simplicity)

server.on('connection', function (socket) {
  console.log("Welcomed Connection from: " + socket.remoteAddress);

  socket.on('close', function (resp) {
    console.log(`[${GetDate(3)}] Bye!`);
  });

  socket.on('data', function (buf) {
    // Take Views/URL from Front-end.
    // Initialise a new Object from ViewClass and let it run until finished.
  });
});

Lets say I receive data from the WebSocket and that data creates a new ViewClass object and starts running immediately. Will that Now Running code block the input/output of the Node.js Server? Or will it be handled in the background?

If there is any information I can provide to make it clearer let me know as I am extremely new to Websocket/Js and I am more than likely missing information.

Brad Larson
  • 170,088
  • 45
  • 397
  • 571

1 Answers1

0

Your ViewClass code is launching views XMLHttpRequests and then doing nothing, but waiting for responses to come back. Because a regular XMLHttpRequest is asynchronous (if you don't pass false for the async flag), the server is free to do other things while the code is waiting for the XMLHttpRequest responses.

Will that Now Running code block the input/output of the Node.js Server?

No, because this is asynchronous code, it will not block the input/output of the server.

Or will it be handled in the background?

Responses themselves are not handled in the background. Nodejs runs your Javascript in a single thread (assuming there are no WorkerThreads being used which are not being used here). But, waiting for a networking response is asynchronous and is handled by native code in the event loop in the background. So, while your code is doing nothing but waiting for an event to occur, nodejs and your server is free to respond to other incoming events (such as other incoming requests).


Emergency Edit:

This code:

 xhr.open("GET", link, false);

Is attempting a SYNCHRONOUS XMLHttpRequest. That's a horrible thing to do in a node.js server. That WILL block all other activity. Change the false to true to allow the xhr request to be asynchronous.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • This is absolutely what I was looking for, thank you so much. And I'm guessing creating multiple of these objects is okay too? This would be public so people would be regularly using this and more than 1 ViewClass Object could be created. –  Aug 09 '20 at 22:45
  • 1
    "*Because an `XMLHttpRequest` is asynchronous, the server is free to do other things while the code is waiting*" - huh? The `XMLHttpRequest` is running on the client side, where it doesn't block the browser's main rendering thread, but that has nothing to do with how the nodejs server handles requests. – Bergi Aug 09 '20 at 22:46
  • Oh wait, the `XMLHttpRequest` that the OP is does indeed run on the server, I missed that. It's pretty weird though – Bergi Aug 09 '20 at 22:48
  • I can't have the requests being handled Client-Side so I have to rethink how web-sockets work. I need the server to be handling all information. The websocket file I linked above is on the Node.js server. Not on the clients end. Edit: Just seen you changed your response, my bad haha. –  Aug 09 '20 at 22:49
  • However, doesn't `xhr.open("GET", link, false);` create a *synchronous* request? I wonder how that is even possible in node.js. – Bergi Aug 09 '20 at 22:50
  • Yes I was told by a friend to look into Bot-Factory. My over-all goal is to take info from the client side (Communicated through PHP) and handle it to the nodejs server to Send GET Requests to a website. But I need a way to handle multiple functions running at once as with many people submitting data it might be a bit overwhelming. Thanks for all the help and I'll try my best to get this to work. (Also I would use PHP for handling requests also but it holds up the webpage and I don't wanna keep my customers waiting) –  Aug 09 '20 at 22:52
  • @Bergi - I didn't notice that flag (since it should pretty much never be used). This is an XMLHttpRequest simulation library in node.js. Does that really support synchronous requests? I can't find any doc to that effect. – jfriend00 Aug 09 '20 at 22:53
  • @jfriend00 Let's find out! – Bergi Aug 09 '20 at 22:54
  • @Bergi - I looked at the code and apparently it does. It uses `spawn()` and a polling loop. – jfriend00 Aug 09 '20 at 22:56
  • [Whoa](https://github.com/driverdan/node-XMLHttpRequest/blob/master/lib/XMLHttpRequest.js#L477-L515). Ouch. Looks like you will need to revise your answer. – Bergi Aug 09 '20 at 22:57
  • @sus - See what I added to my answer. You are attempting to use the SYNCHRONOUS flag with XMLHttpRequest which will block the entire process. Change that boolean to `true` and you won't have that problem. – jfriend00 Aug 09 '20 at 22:59
  • If the requests aren't Asynchronous they start to get dropped after around 5-10 requests. Back to the drawing board with this mess ‍♂️ Thanks for all the help guys. The joys of coding ;D –  Aug 09 '20 at 23:01
  • @jfriend00 "*…and you won't have that problem*" - but [other problems](https://stackoverflow.com/q/750486/1048572) :P – Bergi Aug 09 '20 at 23:01
  • @Sus - Well, that's because your asynchronous code probably isn't written properly or you're overwhelming the target with too many requests, etc... You have to write GOOD asynchronous code if you want it to work properly. – jfriend00 Aug 09 '20 at 23:02
  • @Sus - For starters, you need to put `const xhr = new XMLHttpRequest();` inside the loop. – jfriend00 Aug 09 '20 at 23:03
  • My bad I'll just write good code. Never knew it was that simple. Thanks for the advice. –  Aug 09 '20 at 23:03
  • @Sus - What I meant was if you have a specific problem when you make it asynchronous, then why don't you post what that specific problem is and we could help you with that. Sorry for the previous comment - that was out of place. FYI, `XMLHttpRequest` is a pretty dated and not friendly API. If you're just trying to make http requests to another server from within nodejs, I'd suggest a more modern API like [`got()`](https://www.npmjs.com/package/got) which uses promises and would allow you to sequence your loop using `await` (in a non-blocking way) if you wanted. – jfriend00 Aug 09 '20 at 23:04
  • Because I didn't know it was a problem until you brought it up a few comments ago. I have absolutely no idea what I am doing with any of these technologies and i'm really trying my best. Its all apart of the learning process. –  Aug 09 '20 at 23:05
  • I have also just tried the got library but it has the exact same issue. It dropped 4/10 requests that I sent. –  Aug 09 '20 at 23:15
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/219519/discussion-between-sus-and-jfriend00). –  Aug 09 '20 at 23:29
  • When you tried `got()`, what does "dropped" the requests mean? What output did you get? Did you get error responses? Did you have appropriate error handling. We can't really help you debug the `got()` version of the code that you haven't shown us. – jfriend00 Aug 10 '20 at 03:11