npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

sync-request-curl

v3.0.1

Published

Fast way to send synchronous web requests in NodeJS. API is a subset of sync-request. Leverages node-libcurl for high performance. Cannot be used in a browser.

Downloads

8,175

Readme

Sync Request Curl

pipeline   codecov   Maintainability   Snyk Security   GitHub top language

NPM Version   install size   Depfu Dependencies   FOSSA Status   NPM License   GitHub issues

Quality Gate Status   Codacy Badge   DeepSource   codebeat badge   GitHub stars

Downloads Total   Downloads Yearly   Downloads Monthly   Downloads Weekly   Downloads Daily


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.

Try with Replit


1. Installation

npm install sync-request-curl

Please refer to the compatibility section for known issues and workarounds for Windows, MacOS and Linux.

2. Usage

Try with Replit.

request(method, url, options);

GET request without options

import request from 'sync-request-curl';

const res = request(
  'GET',
  'https://comp1531namesages.alwaysdata.net'
);
console.log('Status Code:', res.statusCode);
const jsonBody = JSON.parse(res.body.toString());
console.log('Returned JSON object:', jsonBody);

GET request with query string parameters

import request from 'sync-request-curl';

const res = request(
  'GET',
  'https://comp1531forum.alwaysdata.net/echo/echo',
  {
    qs: { message: 'Hello, world!' },
  }
);
console.log('Status Code:', res.statusCode);
const jsonBody = JSON.parse(res.body.toString());
console.log('Returned JSON object:', jsonBody);

POST request with headers and JSON payload

import request from 'sync-request-curl';

const res = request(
  'POST',
  'https://comp1531quiz.alwaysdata.net/quiz/create',
  {
    headers: { lab08quizsecret: "bruno's fight club" },
    json: {
      quizTitle: 'New Quiz',
      quizSynopsis: 'Sync request curl example'
    },
  }
);
console.log('Status Code:', res.statusCode);
const jsonBody = JSON.parse(res.body.toString());
console.log('Returned JSON Object:', jsonBody);

Using a proxy URL (Note: replace with your own proxy details)

import request from 'sync-request-curl';

const res = request(
  'GET',
  'https://ipinfo.io/json',
  {
    setEasyOptions: (curl, options) => {
      curl.setOpt(options.PROXY, 'http://your-proxy-url:port');
      curl.setOpt(options.PROXYUSERPWD, 'proxyUsername:proxyPassword');
    },
  }
);

console.log('Status Code:', res.statusCode);
const jsonBody = JSON.parse(res.body.toString());
console.log(jsonBody);

2.1. Method

HTTP method (of type HttpVerb)

  • e.g. PUT/POST/GET/DELETE

Note that for the HEAD method, CURLOPT_NOBODY is set to true automatically by sync-request-curl.

2.2. URL

URL as a string

  • e.g. https://toohak.fly.dev

2.3. Options

Only the following options from sync-request are supported for the time being:

Below are some additional options available from node-libcurl:

In src/types.ts, the Options interface following is defined as:

export interface Options {
  /*
   * sync-request options
   */
  headers?: IncomingHttpHeaders;
  qs?: { [key: string]: any };
  json?: any;
  body?: string | Buffer;

  timeout?: number;
  followRedirects?: boolean;
  maxRedirects?: number;

  /*
   * node-libcurl options
   */
  insecure?: boolean;
  setEasyOptions?: SetEasyOptionCallback;
}

2.4. Response

  • 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 object
  • getBody - 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 instead
  • url - the final URL used in the request after all redirections are followed, and with the query string parameters appended

In src/types.ts, the Response interface is defined as:

export interface Response {
  statusCode: number;
  headers: IncomingHttpHeaders;
  body: string | Buffer;
  getBody: (encoding?: BufferEncoding) => string | Buffer; // simplified
  url: string;
}

2.5. Errors

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:

  • https://curl.se/libcurl/c/libcurl-errors.html

A few common errors are:

  1. CURLE_COULDNT_CONNECT (7)
    • Failed to connect() to host or proxy.
    • HINT: This means that the server could not be reached. For local development (e.g. in testing), ensure that your server has started successfully, or that it did not crash while handling a previous request
  2. CURLE_URL_MALFORMAT (3)
    • The URL was not properly formatted.
    • HINT: The request was not successful because your input URL is invalid, e.g. missing domain, protocol or port. Try printing out your input URL, or if it is a GET request, access it directly in a browser
  3. CURLE_PEER_FAILED_VERIFICATION (60)
    • The remote server's SSL certificate or SSH fingerprint was deemed not OK. This error code has been unified with CURLE_SSL_CACERT since 7.62.0. Its previous value was 51
    • HINT: See the Windows compatibility section for an explanation and potential workaround

It is possible to check the cURL code as follows:

import request, { CurlError } from 'sync-request-curl';

try {
  request('GET', 'https://google.fake.url.com');
} catch (error) {
  if (error instanceof CurlError) {
    // outputs 6 (CURLE_COULDNT_RESOLVE_HOST)
    console.log(error.code);
  }
}

In src/errors.ts, the CurlError class is defined as:

export class CurlError extends Error {
  // https://curl.se/libcurl/c/libcurl-errors.html
  code: number;
  constructor(code: number, message: string) {
    super(message);
    if (code < 1 || code > 99) {
      throw new Error(`CurlError code must be between 1 and 99. Given: ${code}`);
    }
    this.code = code;
    Object.setPrototypeOf(this, CurlError.prototype);
  }
}

3. License

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.

FOSSA Status

4. Compatibility

4.1. Windows

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:

  • https://github.com/JCMais/node-libcurl/issues/301
  • https://stackoverflow.com/a/34883260/22324694

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).

4.2. MacOS

The build for MacOS may fail during the installation process.

In most cases, this can be fixed by following these Github issues:

  • https://github.com/JCMais/node-libcurl/issues/296
  • https://github.com/JCMais/node-libcurl/issues/382

and carefully reviewing the MacOS Build Requirements from node-libcurl's documentation. Otherwise, we recommend uninstalling this library and installing sync-request.

4.3. Linux

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:

  • https://github.com/JCMais/node-libcurl/issues/374
  • https://github.com/JCMais/node-libcurl/issues/376

Be sure to also check the Linux Build Requirements from node-libcurl's documentation.

5. Caveats

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.