• Stars
    star
    130
  • Rank 277,575 (Top 6 %)
  • Language
    JavaScript
  • License
    Other
  • Created about 7 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

like fetch() but for the npm registry

npm-registry-fetch

npm-registry-fetch is a Node.js library that implements a fetch-like API for accessing npm registry APIs consistently. It's able to consume npm-style configuration values and has all the necessary logic for picking registries, handling scopes, and dealing with authentication details built-in.

This package is meant to replace the older npm-registry-client.

Example

const npmFetch = require('npm-registry-fetch')

console.log(
  await npmFetch.json('/-/ping')
)

Table of Contents

Install

$ npm install npm-registry-fetch

Contributing

The npm team enthusiastically welcomes contributions and project participation! There's a bunch of things you can do if you want to contribute! The Contributor Guide has all the information you need for everything from reporting bugs to contributing entire new features. Please don't hesitate to jump in if you'd like to, or even ask us questions if something isn't clear.

All participants and maintainers in this project are expected to follow Code of Conduct, and just generally be excellent to each other.

Please refer to the Changelog for project history details, too.

Happy hacking!

API

Caching and write=true query strings

Before performing any PUT or DELETE operation, npm clients first make a GET request to the registry resource being updated, which includes the query string ?write=true.

The semantics of this are, effectively, "I intend to write to this thing, and need to know the latest current value, so that my write can land cleanly".

The public npm registry handles these ?write=true requests by ensuring that the cache is re-validated before sending a response. In order to maintain the same behavior on the client, and not get tripped up by an overeager local cache when we intend to write data to the registry, any request that comes through npm-registry-fetch that contains write=true in the query string will forcibly set the prefer-online option to true, and set both prefer-offline and offline to false, so that any local cached value will be revalidated.

> fetch(url, [opts]) -> Promise<Response>

Performs a request to a given URL.

The URL can be either a full URL, or a path to one. The appropriate registry will be automatically picked if only a URL path is given.

For available options, please see the section on fetch options.

Example
const res = await fetch('/-/ping')
console.log(res.headers)
res.on('data', d => console.log(d.toString('utf8')))

> fetch.json(url, [opts]) -> Promise<ResponseJSON>

Performs a request to a given registry URL, parses the body of the response as JSON, and returns it as its final value. This is a utility shorthand for fetch(url).then(res => res.json()).

For available options, please see the section on fetch options.

Example
const res = await fetch.json('/-/ping')
console.log(res) // Body parsed as JSON

> fetch.json.stream(url, jsonPath, [opts]) -> Stream

Performs a request to a given registry URL and parses the body of the response as JSON, with each entry being emitted through the stream.

The jsonPath argument is a JSONStream.parse() path, and the returned stream (unlike default JSONStreams), has a valid Symbol.asyncIterator implementation.

For available options, please see the section on fetch options.

Example
console.log('https://npm.im/~zkat has access to the following packages:')
for await (let {key, value} of fetch.json.stream('/-/user/zkat/package', '$*')) {
  console.log(`https://npm.im/${key} (perms: ${value})`)
}

fetch Options

Fetch options are optional, and can be passed in as either a Map-like object (one with a .get() method), a plain javascript object, or a figgy-pudding instance.

opts.agent
  • Type: http.Agent
  • Default: an appropriate agent based on URL protocol and proxy settings

An Agent instance to be shared across requests. This allows multiple concurrent fetch requests to happen on the same socket.

You do not need to provide this option unless you want something particularly specialized, since proxy configurations and http/https agents are already automatically managed internally when this option is not passed through.

opts.body
  • Type: Buffer | Stream | Object
  • Default: null

Request body to send through the outgoing request. Buffers and Streams will be passed through as-is, with a default content-type of application/octet-stream. Plain JavaScript objects will be JSON.stringifyed and the content-type will default to application/json.

Use opts.headers to set the content-type to something else.

opts.ca
  • Type: String, Array, or null
  • Default: null

The Certificate Authority signing certificate that is trusted for SSL connections to the registry. Values should be in PEM format (Windows calls it "Base-64 encoded X.509 (.CER)") with newlines replaced by the string '\n'. For example:

{
  ca: '-----BEGIN CERTIFICATE-----\nXXXX\nXXXX\n-----END CERTIFICATE-----'
}

Set to null to only allow "known" registrars, or to a specific CA cert to trust only that specific signing authority.

Multiple CAs can be trusted by specifying an array of certificates instead of a single string.

See also opts.strictSSL, opts.ca and opts.key

opts.cache
  • Type: path
  • Default: null

The location of the http cache directory. If provided, certain cachable requests will be cached according to IETF RFC 7234 rules. This will speed up future requests, as well as make the cached data available offline if necessary/requested.

See also offline, preferOffline, and preferOnline.

opts.cert
  • Type: String
  • Default: null

A client certificate to pass when accessing the registry. Values should be in PEM format (Windows calls it "Base-64 encoded X.509 (.CER)") with newlines replaced by the string '\n'. For example:

{
  cert: '-----BEGIN CERTIFICATE-----\nXXXX\nXXXX\n-----END CERTIFICATE-----'
}

It is not the path to a certificate file (and there is no "certfile" option).

See also: opts.ca and opts.key

opts.fetchRetries
  • Type: Number
  • Default: 2

The "retries" config for retry to use when fetching packages from the registry.

See also opts.retry to provide all retry options as a single object.

opts.fetchRetryFactor
  • Type: Number
  • Default: 10

The "factor" config for retry to use when fetching packages.

See also opts.retry to provide all retry options as a single object.

opts.fetchRetryMintimeout
  • Type: Number
  • Default: 10000 (10 seconds)

The "minTimeout" config for retry to use when fetching packages.

See also opts.retry to provide all retry options as a single object.

opts.fetchRetryMaxtimeout
  • Type: Number
  • Default: 60000 (1 minute)

The "maxTimeout" config for retry to use when fetching packages.

See also opts.retry to provide all retry options as a single object.

opts.forceAuth
  • Type: Object
  • Default: null

If present, other auth-related values in opts will be completely ignored, including alwaysAuth, email, and otp, when calculating auth for a request, and the auth details in opts.forceAuth will be used instead.

opts.gzip
  • Type: Boolean
  • Default: false

If true, npm-registry-fetch will set the Content-Encoding header to gzip and use zlib.gzip() or zlib.createGzip() to gzip-encode opts.body.

opts.headers
  • Type: Object
  • Default: null

Additional headers for the outgoing request. This option can also be used to override headers automatically generated by npm-registry-fetch, such as Content-Type.

opts.ignoreBody
  • Type: Boolean
  • Default: false

If true, the response body will be thrown away and res.body set to null. This will prevent dangling response sockets for requests where you don't usually care what the response body is.

opts.integrity

If provided, the response body's will be verified against this integrity string, using ssri. If verification succeeds, the response will complete as normal. If verification fails, the response body will error with an EINTEGRITY error.

Body integrity is only verified if the body is actually consumed to completion -- that is, if you use res.json()/res.buffer(), or if you consume the default res stream data to its end.

Cached data will have its integrity automatically verified using the previously-generated integrity hash for the saved request information, so EINTEGRITY errors can happen if opts.cache is used, even if opts.integrity is not passed in.

opts.key
  • Type: String
  • Default: null

A client key to pass when accessing the registry. Values should be in PEM format with newlines replaced by the string '\n'. For example:

{
  key: '-----BEGIN PRIVATE KEY-----\nXXXX\nXXXX\n-----END PRIVATE KEY-----'
}

It is not the path to a key file (and there is no "keyfile" option).

See also: opts.ca and opts.cert

opts.localAddress
  • Type: IP Address String
  • Default: null

The IP address of the local interface to use when making connections to the registry.

See also opts.proxy

opts.mapJSON
  • Type: Function
  • Default: undefined

When using fetch.json.stream() (NOT fetch.json()), this will be passed down to JSONStream as the second argument to JSONStream.parse, and can be used to transform stream data before output.

opts.maxSockets
  • Type: Integer
  • Default: 12

Maximum number of sockets to keep open during requests. Has no effect if opts.agent is used.

opts.method
  • Type: String
  • Default: 'GET'

HTTP method to use for the outgoing request. Case-insensitive.

opts.noProxy
  • Type: String | String[]
  • Default: process.env.NOPROXY

If present, should be a comma-separated string or an array of domain extensions that a proxy should not be used for.

opts.npmSession
  • Type: String
  • Default: null

If provided, will be sent in the npm-session header. This header is used by the npm registry to identify individual user sessions (usually individual invocations of the CLI).

opts.npmCommand
  • Type: String
  • Default: null

If provided, it will be sent in the npm-command header. This header is used by the npm registry to identify the npm command that caused this request to be made.

opts.offline
  • Type: Boolean
  • Default: false

Force offline mode: no network requests will be done during install. To allow npm-registry-fetch to fill in missing cache data, see opts.preferOffline.

This option is only really useful if you're also using opts.cache.

This option is set to true when the request includes write=true in the query string.

opts.otp
  • Type: Number | String
  • Default: null

This is a one-time password from a two-factor authenticator. It is required for certain registry interactions when two-factor auth is enabled for a user account.

opts.otpPrompt
  • Type: Function
  • Default: null

This is a method which will be called to provide an OTP if the server responds with a 401 response indicating that a one-time-password is required.

It may return a promise, which must resolve to the OTP value to be used. If the method fails to provide an OTP value, then the fetch will fail with the auth error that indicated an OTP was needed.

opts.password
  • Alias: _password
  • Type: String
  • Default: null

Password used for basic authentication. For the more modern authentication method, please use the (more secure) opts.token

Can optionally be scoped to a registry by using a "nerf dart" for that registry. That is:

{
  '//registry.npmjs.org/:password': 't0k3nH34r'
}

See also opts.username

opts.preferOffline
  • Type: Boolean
  • Default: false

If true, staleness checks for cached data will be bypassed, but missing data will be requested from the server. To force full offline mode, use opts.offline.

This option is generally only useful if you're also using opts.cache.

This option is set to false when the request includes write=true in the query string.

opts.preferOnline
  • Type: Boolean
  • Default: false

If true, staleness checks for cached data will be forced, making the CLI look for updates immediately even for fresh package data.

This option is generally only useful if you're also using opts.cache.

This option is set to true when the request includes write=true in the query string.

opts.scope
  • Type: String
  • Default: null

If provided, will be sent in the npm-scope header. This header is used by the npm registry to identify the toplevel package scope that a particular project installation is using.

opts.proxy
  • Type: url
  • Default: null

A proxy to use for outgoing http requests. If not passed in, the HTTP(S)_PROXY environment variable will be used.

opts.query
  • Type: String | Object
  • Default: null

If provided, the request URI will have a query string appended to it using this query. If opts.query is an object, it will be converted to a query string using querystring.stringify().

If the request URI already has a query string, it will be merged with opts.query, preferring opts.query values.

opts.registry
  • Type: URL
  • Default: 'https://registry.npmjs.org'

Registry configuration for a request. If a request URL only includes the URL path, this registry setting will be prepended.

See also opts.scope, opts.spec, and opts.<scope>:registry which can all affect the actual registry URL used by the outgoing request.

opts.retry
  • Type: Object
  • Default: null

Single-object configuration for request retry settings. If passed in, will override individually-passed fetch-retry-* settings.

opts.scope
  • Type: String
  • Default: null

Associate an operation with a scope for a scoped registry. This option can force lookup of scope-specific registries and authentication.

See also opts.<scope>:registry and opts.spec for interactions with this option.

opts.<scope>:registry
  • Type: String
  • Default: null

This option type can be used to configure the registry used for requests involving a particular scope. For example, opts['@myscope:registry'] = 'https://scope-specific.registry/' will make it so requests go out to this registry instead of opts.registry when opts.scope is used, or when opts.spec is a scoped package spec.

The @ before the scope name is optional, but recommended.

opts.spec

If provided, can be used to automatically configure opts.scope based on a specific package name. Non-registry package specs will throw an error.

opts.strictSSL
  • Type: Boolean
  • Default: true

Whether or not to do SSL key validation when making requests to the registry via https.

See also opts.ca.

opts.timeout
  • Type: Milliseconds
  • Default: 300000 (5 minutes)

Time before a hanging request times out.

opts._authToken
  • Type: String
  • Default: null

Authentication token string.

Can be scoped to a registry by using a "nerf dart" for that registry. That is:

{
  '//registry.npmjs.org/:_authToken': 't0k3nH34r'
}
opts.userAgent
  • Type: String
  • Default: 'npm-registry-fetch@<version>/node@<node-version>+<arch> (<platform>)'

User agent string to send in the User-Agent header.

opts.username
  • Type: String
  • Default: null

Username used for basic authentication. For the more modern authentication method, please use the (more secure) opts.authtoken

Can optionally be scoped to a registry by using a "nerf dart" for that registry. That is:

{
  '//registry.npmjs.org/:username': 't0k3nH34r'
}

See also opts.password

More Repositories

1

npm

This repository is moving to: https://github.com/npm/cli
17,473
star
2

cli

the package manager for JavaScript
JavaScript
8,303
star
3

node-semver

The semver parser for node (the one npm uses)
JavaScript
4,772
star
4

npm-expansions

Send us a pull request by editing expansions.txt
JavaScript
2,209
star
5

tink

a dependency unwinder for javascript
JavaScript
2,153
star
6

ini

An ini parser/serializer in JavaScript
JavaScript
733
star
7

npx

npm package executor
JavaScript
731
star
8

rfcs

Public change requests/proposals & ideation
JavaScript
726
star
9

npm-registry-couchapp

couchapp bits of registry.npmjs.org
JavaScript
615
star
10

nopt

Node/npm Option Parsing
JavaScript
527
star
11

registry

npm registry documentation
449
star
12

npmlog

The logger that npm uses
JavaScript
423
star
13

marky-markdown

npm's markdown parser
JavaScript
405
star
14

arborist

npm's tree doctor
JavaScript
369
star
15

documentation

Documentation for the npm registry, website, and command-line interface.
MDX
369
star
16

pacote

npm fetcher
JavaScript
349
star
17

download-counts

Background jobs and a minimal service for collecting and delivering download counts
JavaScript
328
star
18

gauge

A terminal based horizontal guage aka, a progress bar
JavaScript
319
star
19

node-which

Like which(1) unix command. Find the first instance of an executable in the PATH.
JavaScript
305
star
20

init-package-json

A node module to get your node module started
JavaScript
284
star
21

validate-npm-package-name

Is the given string an acceptable npm package name?
JavaScript
282
star
22

cacache

npm's content-addressable cache
JavaScript
274
star
23

npm-merge-driver

git merge driver for resolving conflicts in npm-related files
JavaScript
271
star
24

npm-registry-client

JavaScript
264
star
25

lockfile

A very polite lock file utility, which endeavors to not litter, and to wait patiently for others.
JavaScript
259
star
26

registry-issue-archive

An archive of the old npm registry issue tracker
250
star
27

write-file-atomic

Write files in an atomic fashion w/configurable ownership
JavaScript
217
star
28

read-package-json

The thing npm uses to read package.json files with semantics and defaults and validation and stuff
JavaScript
214
star
29

roadmap

Public roadmap for npm
213
star
30

hosted-git-info

Provides metadata and conversions from repository urls for Github, Bitbucket and Gitlab
JavaScript
206
star
31

fstream

Advanced FS Streaming for Node
JavaScript
205
star
32

make-fetch-happen

making fetch happen for npm
JavaScript
190
star
33

read

read(1) for node.
JavaScript
187
star
34

normalize-package-data

normalizes package metadata, typically found in package.json file.
JavaScript
184
star
35

ndm

ndm allows you to deploy OS-specific service-wrappers directly from npm-packages.
JavaScript
181
star
36

are-we-there-yet

Track complex hiearchies of asynchronous task completion statuses.
JavaScript
173
star
37

abbrev-js

Like ruby's Abbrev module
JavaScript
158
star
38

statusboard

Public monitor/status/health board for @npm/cli-team's maintained projects
JavaScript
152
star
39

security-holder

An npm package that holds a spot.
145
star
40

osenv

Look up environment settings specific to different operating systems.
JavaScript
137
star
41

feedback

Public feedback discussions for npm
133
star
42

npm-package-arg

Parse the things that can be arguments to `npm install`
JavaScript
116
star
43

libnpm

programmatic npm API
JavaScript
113
star
44

npm-collection-staff-picks

JavaScript
112
star
45

npm-packlist

Walk through a folder and figure out what goes in an npm package
JavaScript
110
star
46

promzard

A prompting json thingie
JavaScript
101
star
47

npm-remote-ls

Examine a package's dependency graph before you install it
JavaScript
89
star
48

npmconf

npm config thing
JavaScript
75
star
49

cmd-shim

The cmd-shim used in npm
JavaScript
75
star
50

npm-tips

A collection of short (5 words or so) tips and tricks that can be sprinkled about the npm site.
JavaScript
73
star
51

www

community space for the npm website
68
star
52

policies

Privacy policy, code of conduct, license, and other npm legal stuff
Shell
67
star
53

package-json

Programmatic API to update package.json
JavaScript
65
star
54

git

a util for spawning git from npm CLI contexts
JavaScript
62
star
55

npm_conf

A conference about npm, maybe. Not to be confused with npmconf.
59
star
56

ignore-walk

Nested/recursive `.gitignore`/`.npmignore` parsing and filtering.
JavaScript
57
star
57

registry-follower-tutorial

write you a registry follower for great good
JavaScript
56
star
58

ssri

subresource integrity for npm
JavaScript
55
star
59

minipass-fetch

An implementation of window.fetch in Node.js using Minipass streams
JavaScript
54
star
60

ci-detect

Detect what kind of CI environment the program is in
JavaScript
53
star
61

run-script

Run a lifecycle script for a package (descendant of npm-lifecycle)
JavaScript
53
star
62

read-installed

Read all the installed packages in a folder, and return a tree structure with all the data.
JavaScript
52
star
63

mute-stream

Bytes go in, but they don't come out (when muted).
JavaScript
49
star
64

fs-write-stream-atomic

Like `fs.createWriteStream(...)`, but atomic.
JavaScript
48
star
65

read-package-json-fast

Like read-package-json, but faster
JavaScript
48
star
66

libnpmpublish

programmatically publish and unpublish npm packages
JavaScript
46
star
67

logical-tree

Calculates a nested logical tree using a package.json and a package lock.
JavaScript
44
star
68

read-package-tree

Read the contents of node_modules
JavaScript
42
star
69

jobs

41
star
70

unique-filename

Generate a unique filename for use in temporary directories or caches.
JavaScript
40
star
71

lock-verify

Report if your package.json is out of sync with your package-lock.json
JavaScript
38
star
72

fstream-ignore

JavaScript
37
star
73

benchmarks

The npm CLI's benchmark suite
JavaScript
36
star
74

npm-lifecycle

npm lifecycle script runner
JavaScript
36
star
75

wombat-cli

The wombat cli tool.
JavaScript
35
star
76

npme-installer

npm Enterprise installer
JavaScript
35
star
77

couch-login

A module for doing logged-in requests against a couchdb server
JavaScript
33
star
78

libnpmexec

npm exec (npx) Programmatic API
JavaScript
33
star
79

npm-audit-report

npm audit security report
JavaScript
33
star
80

ansible-nagios

Ansible role for building Nagios 4.
Perl
32
star
81

config

Configuration management for https://github.com/npm/cli
JavaScript
32
star
82

parse-conflict-json

Parse a JSON string that has git merge conflicts, resolving if possible
JavaScript
32
star
83

npm-profile

Make changes to your npmjs.com profile via cli or library
JavaScript
31
star
84

unique-slug

Generate a unique character string suitible for use in files and URLs.
JavaScript
31
star
85

fstream-npm

fstream class for creating npm packages
JavaScript
30
star
86

redsess

Yet another redis session thing for node.
JavaScript
30
star
87

concurrent-couch-follower

a couch follower wrapper that you can use to be sure you don't miss any documents even if you process them asynchronously.
JavaScript
28
star
88

npm-registry-mock

mock the npm registry
JavaScript
27
star
89

lint

lint the npmcli way
JavaScript
26
star
90

fs

filesystem helper functions, wrappers, and promisification for the npm cli
JavaScript
25
star
91

template-oss

a template package for npm CLI team development
JavaScript
25
star
92

libnpmsearch

programmatic API for the shiny new npm search endpoint
JavaScript
25
star
93

bin-links

.bin/ script linker
JavaScript
24
star
94

libnpmaccess

programmatic api for `npm access`
JavaScript
24
star
95

logos

official logos for npm, Inc
22
star
96

types

Typescript definitions for npm registry content
JavaScript
22
star
97

public-api

21
star
98

deprecate-holder

An npm package that holds a spot.
21
star
99

map-workspaces

Retrieves a name:pathname Map for a given workspaces config
JavaScript
20
star
100

libnpmversion

library to do the things that 'npm version' does
JavaScript
20
star