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.
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.
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.
XMLHttpRequest supports both synchronous and asynchronous communications.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With