Gathering detailed insights and metrics for sync-request-curl
Gathering detailed insights and metrics for sync-request-curl
Gathering detailed insights and metrics for sync-request-curl
Gathering detailed insights and metrics for sync-request-curl
Make synchronous web requests similar to sync-request, but 20 times more quickly. Leverages node-libcurl for performance instead of spawning child processes like sync-request. This library was designed to run on NodeJS. It will not work in a browser.
npm install sync-request-curl
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
8 Stars
497 Commits
1 Forks
2 Watching
1 Branches
4 Contributors
Updated on 24 Nov 2024
TypeScript (74.76%)
JavaScript (25.24%)
Cumulative downloads
Total Downloads
Last day
-57.2%
263
Compared to previous day
Last week
-92.7%
2,401
Compared to previous week
Last month
19.9%
93,224
Compared to previous month
Last year
271.6%
412,799
Compared to previous year
1
Make synchronous web requests similar to sync-request, but 20 times more quickly.
Leverages node-libcurl for performance instead of spawning child processes like sync-request.
This library was designed to run on NodeJS. It will not work in a browser.
npm install sync-request-curl
Please refer to the compatibility section for known issues and workarounds for Windows, MacOS and Linux.
Try with Replit.
1request(method, url, options);
GET
request without options
1import request from 'sync-request-curl'; 2 3const res = request( 4 'GET', 5 'https://comp1531namesages.alwaysdata.net' 6); 7console.log('Status Code:', res.statusCode); 8const jsonBody = JSON.parse(res.body.toString()); 9console.log('Returned JSON object:', jsonBody);
GET
request with query string parameters
1import request from 'sync-request-curl'; 2 3const res = request( 4 'GET', 5 'https://comp1531forum.alwaysdata.net/echo/echo', 6 { 7 qs: { message: 'Hello, world!' }, 8 } 9); 10console.log('Status Code:', res.statusCode); 11const jsonBody = JSON.parse(res.body.toString()); 12console.log('Returned JSON object:', jsonBody);
POST
request with headers and JSON payload
1import request from 'sync-request-curl'; 2 3const res = request( 4 'POST', 5 'https://comp1531quiz.alwaysdata.net/quiz/create', 6 { 7 headers: { lab08quizsecret: "bruno's fight club" }, 8 json: { 9 quizTitle: 'New Quiz', 10 quizSynopsis: 'Sync request curl example' 11 }, 12 } 13); 14console.log('Status Code:', res.statusCode); 15const jsonBody = JSON.parse(res.body.toString()); 16console.log('Returned JSON Object:', jsonBody);
Using a proxy URL (Note: replace with your own proxy details)
1import request from 'sync-request-curl'; 2 3const res = request( 4 'GET', 5 'https://ipinfo.io/json', 6 { 7 setEasyOptions: (curl, options) => { 8 curl.setOpt(options.PROXY, 'http://your-proxy-url:port'); 9 curl.setOpt(options.PROXYUSERPWD, 'proxyUsername:proxyPassword'); 10 }, 11 } 12); 13 14console.log('Status Code:', res.statusCode); 15const jsonBody = JSON.parse(res.body.toString()); 16console.log(jsonBody);
HTTP method (of type HttpVerb
)
PUT
/POST
/GET
/DELETE
Note that for the HEAD
method, CURLOPT_NOBODY is set to true
automatically by sync-request-curl.
URL as a string
Only the following options from sync-request are supported for the time being:
Option | Description | Example | Default |
---|---|---|---|
qs | An object containing query string parameters which will be appended to the URL. |
{ message: 'Hi!' } | undefined |
headers | HTTP headers for the request. |
{ token: 'abcde' } | undefined |
json |
Sets the body as a JSON representation of the value and automatically adds Content-type: application/json to the header. |
{ name: 'Tam', course: 1531 } | undefined |
body |
String body for PATCH, POST and PUT requests. We recommended using json instead for JSON payloads, otherwise the Content-Type will need to be set manually.
|
JSON.stringify({ name: 'Tam', course: 1531 }) | undefined |
timeout | Times out if no response is returned within the given number of milliseconds. | 2000 | 0 (no timeout) |
followRedirects | Sets whether redirects (status code 302) should be followed automatically. | false | true |
maxRedirects | Sets the maximum number of redirects to follow before throwing an Error. | 3 | -1 (no limit) |
Below are some additional options available from node-libcurl:
Option | Description | Example | Default |
---|---|---|---|
insecure | Set to true to send insecure requests. This can be useful on Windows which may have SSL issues (Libcurl code 60). | true | false |
setEasyOptions | Optional callback to set additional curl options for the Easy Interface. This has priority over existing options. |
(curl, opt) => { curl.setOpt( opt.URL, 'www.ck' ); } | undefined |
In src/types.ts, the Options
interface following is defined as:
1export interface Options { 2 /* 3 * sync-request options 4 */ 5 headers?: IncomingHttpHeaders; 6 qs?: { [key: string]: any }; 7 json?: any; 8 body?: string | Buffer; 9 10 timeout?: number; 11 followRedirects?: boolean; 12 maxRedirects?: number; 13 14 /* 15 * node-libcurl options 16 */ 17 insecure?: boolean; 18 setEasyOptions?: SetEasyOptionCallback; 19}
statusCode
- a number representing the HTTP status code (e.g. 200
, 400
, 401
, 403
)headers
- HTTP response headers. The keys/properties of the object will always be in lowercase, e.g. "content-type"
instead of "Content-Type"
body
- a string or buffer - for JSON responses, use JSON.parse(response.body.toString())
to get the returned data as an objectgetBody
- a function with an optional encoding
argument that returns the body
if encoding
is undefined, otherwise body.toString(encoding)
. If statusCode >= 300
, an Error
is thrown insteadurl
- the final URL used in the request after all redirections are followed, and with the query string parameters appendedIn src/types.ts, the Response
interface is defined as:
1export interface Response { 2 statusCode: number; 3 headers: IncomingHttpHeaders; 4 body: string | Buffer; 5 getBody: (encoding?: BufferEncoding) => string | Buffer; // simplified 6 url: string; 7}
When using the response.getBody()
function, a generic Error object is thrown.
If there are issues with the request, a CurlError
will be thrown. This will contain a non-zero code
property that corresponds to a specific Libcurl Error from this documentation:
A few common errors are:
It is possible to check the cURL code as follows:
1import request, { CurlError } from 'sync-request-curl'; 2 3try { 4 request('GET', 'https://google.fake.url.com'); 5} catch (error) { 6 if (error instanceof CurlError) { 7 // outputs 6 (CURLE_COULDNT_RESOLVE_HOST) 8 console.log(error.code); 9 } 10}
In src/errors.ts, the CurlError
class is defined as:
1export class CurlError extends Error { 2 // https://curl.se/libcurl/c/libcurl-errors.html 3 code: number; 4 constructor(code: number, message: string) { 5 super(message); 6 if (code < 1 || code > 99) { 7 throw new Error(`CurlError code must be between 1 and 99. Given: ${code}`); 8 } 9 this.code = code; 10 Object.setPrototypeOf(this, CurlError.prototype); 11 } 12}
Copyright (c) 2023 Khiet Tam Nguyen
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
For installation issues, be sure to review the Windows Build Requirements from node-libcurl's documentation.
In addition, your requests may unexpectedly fail with a Libcurl Error (code 60, CURLE_PEER_FAILED_VERIFICATION) when using NodeJS natively on Windows.
The reason is covered in the below resources:
One quick workaround is to set the insecure
option to true
when sending your requests. This is the same as setting the Libcurl Easy's equivalent SSL_VERIFYPEER to 0
, or using curl
in the command line with the -k
or --insecure
option.
Alternatively, consider using Windows Subsystem for Linux (WSL).
The build for MacOS may fail during the installation process.
In most cases, this can be fixed by following these Github issues:
and carefully reviewing the MacOS Build Requirements from node-libcurl's documentation. Otherwise, we recommend uninstalling this library and installing sync-request.
In rare cases, the build for distributions such as Debian or Ubuntu may fail. This is attributed to missing dependencies such as Python or Libcurl. Below are some related issues:
Be sure to also check the Linux Build Requirements from node-libcurl's documentation.
See sync-request for the original documentation. Please note that sync-request-curl only supports a subset of the original features in sync-request and additional features through leveraging node-libcurl.
sync-request-curl was developed to improve performance with sending synchronous requests in NodeJS. It is also free from the sync-request bug which leaves an orphaned sync-rpc process, resulting in a leaked handle being detected in Jest.
sync-request-curl was designed to work with UNIX-like systems for UNSW students enrolled in COMP1531 Software Engineering Fundamentals. It has been tested on Alpine, Arch, Debian and Ubuntu Linux and is compatible with Windows/MacOS.
Please note that this library's primary goal is to simplify the learning of JavaScript for novice programmers, hence its synchronous nature. However, we recommend to always use an asynchronous alternative where possible.
No vulnerabilities found.
No security vulnerabilities found.