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

native-fetch-cookies

v3.2.2

Published

node-fetch wrapper that adds support for cookie-jars

Downloads

13

Readme

node-fetch-cookies

A node-fetch wrapper with support for cookies. It supports reading/writing from/to a JSON cookie jar and keeps cookies in memory until you call CookieJar.save() to reduce disk I/O.

Usage Examples

with file...

import {fetch, CookieJar} from "node-fetch-cookies";

(async () => {
    // creates a CookieJar instance
    const cookieJar = new CookieJar("jar.json");

    // usual fetch usage, except with one or multiple cookie jars as first parameter
    const response = await fetch(cookieJar, "https://example.com");

    // save the received cookies to disk
    await cookieJar.save();
})();

On the next start cookieJar.load() can be used to load the cookies from the saved file.

...or without

import {fetch, CookieJar} from "node-fetch-cookies";

(async () => {
    const cookieJar = new CookieJar();

    // log in to some api
    let response = await fetch(cookieJar, "https://example.com/api/login", {
        method: "POST",
        body: "credentials"
    });

    // do some requests you require login for
    response = await fetch(
        cookieJar,
        "https://example.com/api/admin/drop-all-databases"
    );

    // and optionally log out again
    response = await fetch(cookieJar, "https://example.com/api/logout");
})();

Exports

This module exports the following classes/functions:

Documentation

async fetch(cookieJars, url[, options])

  • cookieJars A CookieJar instance, an array of CookieJar instances or null, if you don't want to send or store cookies.
  • url and options as in https://github.com/node-fetch/node-fetch#fetchurl-options

Returns a Promise resolving to a Response instance on success.

Class: CookieJar

A class that stores cookies.

Properties

  • flags The read/write flags as specified below.
  • file The path of the cookie jar on the disk.
  • cookies A Map mapping hostnames to maps, which map cookie names to the respective Cookie instance.
  • cookieIgnoreCallback The callback function passed to new CookieJar(), that is called whenever a cookie couldn't be parsed.

new CookieJar([file, flags = rw, cookies, cookieIgnoreCallback])

  • file An optional string containing a relative or absolute path to the file on the disk to use.
  • flags An optional string specifying whether cookies should be read and/or written from/to the jar when passing it as parameter to fetch. Default: rw
    • r: only read from this jar
    • w: only write to this jar
    • rw or wr: read/write from/to this jar
  • cookies An optional initializer for the cookie jar - either an array of Cookie instances or a single Cookie instance.
  • cookieIgnoreCallback(cookie, reason) An optional callback function which will be called when a cookie is ignored instead of added to the cookie jar.
    • cookie The cookie string
    • reason A string containing the reason why the cookie has been ignored

addCookie(cookie[, fromURL])

Adds a cookie to the jar.

  • cookie A Cookie instance to add to the cookie jar. Alternatively this can also be a string, for example a serialized cookie received from a website. In this case fromURL must be specified.
  • fromURL The url a cookie has been received from.

Returns true if the cookie has been added successfully. Returns false otherwise.
If the parser throws a CookieParseError, it will be caught and cookieIgnoreCallback will be called with the respective cookie string and error message.

domains()

Returns an iterator over all domains currently stored cookies for.

*cookiesDomain(domain)

Returns an iterator over all cookies currently stored for domain.

*cookiesValid(withSession)

Returns an iterator over all valid (non-expired) cookies.

  • withSession: A boolean. Iterator will include session cookies if set to true.

*cookiesAll()

Returns an iterator over all cookies currently stored.

*cookiesValidForRequest(requestURL)

Returns an iterator over all cookies valid for a request to url.

deleteExpired(sessionEnded)

Removes all expired cookies from the jar.

  • sessionEnded: A boolean. Also removes session cookies if set to true.

async load([file = this.file])

Reads cookies from file on the disk and adds the contained cookies.

  • file: Path to the file where the cookies should be saved. Default: this.file, the file that has been passed to the constructor.

async save([file = this.file])

Saves the cookie jar to file on the disk. Only non-expired non-session cookies are saved.

  • file: Path to the file where the cookies should be saved. Default: this.file, the file that has been passed to the constructor.

Class: Cookie

An abstract representation of a cookie.

Properties

  • name The identifier of the cookie.
  • value The value of the cookie.
  • expiry A Date object of the cookies expiry date or null, if the cookie expires with the session.
  • domain The domain the cookie is valid for.
  • path The path the cookie is valid for.
  • secure A boolean value representing the cookie's secure attribute. If set the cookie will only be used for https requests.
  • subdomains A boolean value specifying whether the cookie should be used for requests to subdomains of domain or not.

new Cookie(str, requestURL)

Creates a cookie instance from the string representation of a cookie as send by a webserver.

  • str The string representation of a cookie.
  • url The url the cookie has been received from.

Will throw a CookieParseError if str couldn't be parsed.

static fromObject(obj)

Creates a cookie instance from an already existing object with the same properties.

serialize()

Serializes the cookie, transforming it to name=value so it can be used in requests.

hasExpired(sessionEnded)

Returns whether the cookie has expired or not.

  • sessionEnded: A boolean that specifies whether the current session has ended, meaning if set to true, the function will return true for session cookies.

isValidForRequest(requestURL)

Returns whether the cookie is valid for a request to url.

Class: CookieParseError

The Error that is thrown when the cookie parser located in the constructor of the Cookie class is unable to parse the input.

License

This project is licensed under the MIT license, see LICENSE.