Search code examples
javascriptnode.jsasynchronoushttp-postsynchronous

How to get a synchronuous result from an HTTP request in node.js


I am writing a node module as a wrapper around a Python module (to make that module available from node.js). This module works as a standalone script or as an HTTP server.

When getting data from that script/server my function needs to return a value and can't do something in a callback function. At least that's how I understand it.
(One possible client is a gitbook-plugin, and when that encounters a "block" it has to call the plugin->my-client-module and insert its return value into the generated HTML document.)

So either I'm seeing something wrong because I'm too new to Node.js (coming from Python) or I need a way to make the HTTP request synchronous.

With the standalone script I can easily do it using ChildProcess.spawnSync, but not in an HTTP request.

Well, I know people are always recommending to do things asynchronously in Node, so I'd also be happy about pointers how to achieve my goal that way. As said I expect clients of my module to pass me some data, pass that along to invoke the script or do a POST request on the server and return the processed data to the client.


Solution

  • You can achieve synchronous HTTP requests using web-workers.
    Here is more info on this topic:
    https://developer.mozilla.org/zh-TW/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests#Example_Synchronous_HTTP_request_from_a_Worker


    Edit:

    You can make synchronous requests from Node.Js. The following module should help: https://www.npmjs.com/package/sync-request