Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: Is there a synchronous version of the `http.get` method in node.js?

Is there a synchronous version of the http.get method in node.js?

Something like:

http.getSync({
    host: 'google.com', 
    port: 80, 
    path: '/'
}, function(response){  

});

console.log(response)

Sometimes it would be very useful.

like image 285
Adam Halasz Avatar asked Mar 03 '12 04:03

Adam Halasz


People also ask

Can Nodejs be synchronous?

For synchronous programming, you only need to focus on the call stack. This is the only part of the NodeJS environment that will be working in this case. A callback stack is a data structure that you use to keep track of the execution of all functions that will run inside the program.

How do I make synchronous fetch?

If XMLHttpRequest is also fine, then you can use async: false, which will do a synchronous call. Show activity on this post. If you don't want to use the fetch api you will have to use callbacks, event listeners, XMLHttpRequest. As it's currently written, your answer is unclear.

Is https request asynchronous?

XMLHttpRequest supports both synchronous and asynchronous communications.


1 Answers

There is a sync-request library that is pretty easily to use. Internally it spawns a child process synchronously and uses then-request, so options are similar to that library.

As others have stated, I would caution against using this in your runtime logic. However, it can be very handy for loading configuration.

If you are loading configuration, another strategy can be using a separate script to start your process. Example:

var http = require("http"),
    cp   = require("child_process");

// Starting process
if (process.argv.length < 3) {
    return http.get("http://www.google.com/index.html", function(res) {
        var config = {
            statusCode : res.statusCode,
            headers    : res.headers
        };

        cp.fork(module.filename, [JSON.stringify(config)]);
    });
}

// Config provided
var config = JSON.parse(process.argv[2]);

console.log(config.statusCode);
like image 112
kjv Avatar answered Sep 28 '22 05:09

kjv