1206251795f1e820ff9768f967f4028616c90f8a5ce51e7b634d80feab9de6e46d415fa1ded51c226e068b0fb49db6a5353f5d0441053ab11e019e69b16255 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. # cacache [![npm version](https://img.shields.io/npm/v/cacache.svg)](https://npm.im/cacache) [![license](https://img.shields.io/npm/l/cacache.svg)](https://npm.im/cacache) [![Travis](https://img.shields.io/travis/npm/cacache.svg)](https://travis-ci.org/npm/cacache) [![AppVeyor](https://ci.appveyor.com/api/projects/status/github/npm/cacache?svg=true)](https://ci.appveyor.com/project/npm/cacache) [![Coverage Status](https://coveralls.io/repos/github/npm/cacache/badge.svg?branch=latest)](https://coveralls.io/github/npm/cacache?branch=latest)
  2. [`cacache`](https://github.com/npm/cacache) is a Node.js library for managing
  3. local key and content address caches. It's really fast, really good at
  4. concurrency, and it will never give you corrupted data, even if cache files
  5. get corrupted or manipulated.
  6. On systems that support user and group settings on files, cacache will
  7. match the `uid` and `gid` values to the folder where the cache lives, even
  8. when running as `root`.
  9. It was written to be used as [npm](https://npm.im)'s local cache, but can
  10. just as easily be used on its own.
  11. _Translations: [español](README.es.md)_
  12. ## Install
  13. `$ npm install --save cacache`
  14. ## Table of Contents
  15. * [Example](#example)
  16. * [Features](#features)
  17. * [Contributing](#contributing)
  18. * [API](#api)
  19. * [Using localized APIs](#localized-api)
  20. * Reading
  21. * [`ls`](#ls)
  22. * [`ls.stream`](#ls-stream)
  23. * [`get`](#get-data)
  24. * [`get.stream`](#get-stream)
  25. * [`get.info`](#get-info)
  26. * [`get.hasContent`](#get-hasContent)
  27. * Writing
  28. * [`put`](#put-data)
  29. * [`put.stream`](#put-stream)
  30. * [`put*` opts](#put-options)
  31. * [`rm.all`](#rm-all)
  32. * [`rm.entry`](#rm-entry)
  33. * [`rm.content`](#rm-content)
  34. * Utilities
  35. * [`clearMemoized`](#clear-memoized)
  36. * [`tmp.mkdir`](#tmp-mkdir)
  37. * [`tmp.withTmp`](#with-tmp)
  38. * Integrity
  39. * [Subresource Integrity](#integrity)
  40. * [`verify`](#verify)
  41. * [`verify.lastRun`](#verify-last-run)
  42. ### Example
  43. ```javascript
  44. const cacache = require('cacache')
  45. const fs = require('fs')
  46. const tarball = '/path/to/mytar.tgz'
  47. const cachePath = '/tmp/my-toy-cache'
  48. const key = 'my-unique-key-1234'
  49. // Cache it! Use `cachePath` as the root of the content cache
  50. cacache.put(cachePath, key, '10293801983029384').then(integrity => {
  51. console.log(`Saved content to ${cachePath}.`)
  52. })
  53. const destination = '/tmp/mytar.tgz'
  54. // Copy the contents out of the cache and into their destination!
  55. // But this time, use stream instead!
  56. cacache.get.stream(
  57. cachePath, key
  58. ).pipe(
  59. fs.createWriteStream(destination)
  60. ).on('finish', () => {
  61. console.log('done extracting!')
  62. })
  63. // The same thing, but skip the key index.
  64. cacache.get.byDigest(cachePath, integrityHash).then(data => {
  65. fs.writeFile(destination, data, err => {
  66. console.log('tarball data fetched based on its sha512sum and written out!')
  67. })
  68. })
  69. ```
  70. ### Features
  71. * Extraction by key or by content address (shasum, etc)
  72. * [Subresource Integrity](#integrity) web standard support
  73. * Multi-hash support - safely host sha1, sha512, etc, in a single cache
  74. * Automatic content deduplication
  75. * Fault tolerance (immune to corruption, partial writes, process races, etc)
  76. * Consistency guarantees on read and write (full data verification)
  77. * Lockless, high-concurrency cache access
  78. * Streaming support
  79. * Promise support
  80. * Pretty darn fast -- sub-millisecond reads and writes including verification
  81. * Arbitrary metadata storage
  82. * Garbage collection and additional offline verification
  83. * Thorough test coverage
  84. * There's probably a bloom filter in there somewhere. Those are cool, right? 🤔
  85. ### Contributing
  86. The cacache team enthusiastically welcomes contributions and project participation! There's a bunch of things you can do if you want to contribute! The [Contributor Guide](CONTRIBUTING.md) 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.
  87. All participants and maintainers in this project are expected to follow [Code of Conduct](CODE_OF_CONDUCT.md), and just generally be excellent to each other.
  88. Please refer to the [Changelog](CHANGELOG.md) for project history details, too.
  89. Happy hacking!
  90. ### API
  91. #### <a name="ls"></a> `> cacache.ls(cache) -> Promise<Object>`
  92. Lists info for all entries currently in the cache as a single large object. Each
  93. entry in the object will be keyed by the unique index key, with corresponding
  94. [`get.info`](#get-info) objects as the values.
  95. ##### Example
  96. ```javascript
  97. cacache.ls(cachePath).then(console.log)
  98. // Output
  99. {
  100. 'my-thing': {
  101. key: 'my-thing',
  102. integrity: 'sha512-BaSe64/EnCoDED+HAsh=='
  103. path: '.testcache/content/deadbeef', // joined with `cachePath`
  104. time: 12345698490,
  105. size: 4023948,
  106. metadata: {
  107. name: 'blah',
  108. version: '1.2.3',
  109. description: 'this was once a package but now it is my-thing'
  110. }
  111. },
  112. 'other-thing': {
  113. key: 'other-thing',
  114. integrity: 'sha1-ANothER+hasH=',
  115. path: '.testcache/content/bada55',
  116. time: 11992309289,
  117. size: 111112
  118. }
  119. }
  120. ```
  121. #### <a name="ls-stream"></a> `> cacache.ls.stream(cache) -> Readable`
  122. Lists info for all entries currently in the cache as a single large object.
  123. This works just like [`ls`](#ls), except [`get.info`](#get-info) entries are
  124. returned as `'data'` events on the returned stream.
  125. ##### Example
  126. ```javascript
  127. cacache.ls.stream(cachePath).on('data', console.log)
  128. // Output
  129. {
  130. key: 'my-thing',
  131. integrity: 'sha512-BaSe64HaSh',
  132. path: '.testcache/content/deadbeef', // joined with `cachePath`
  133. time: 12345698490,
  134. size: 13423,
  135. metadata: {
  136. name: 'blah',
  137. version: '1.2.3',
  138. description: 'this was once a package but now it is my-thing'
  139. }
  140. }
  141. {
  142. key: 'other-thing',
  143. integrity: 'whirlpool-WoWSoMuchSupport',
  144. path: '.testcache/content/bada55',
  145. time: 11992309289,
  146. size: 498023984029
  147. }
  148. {
  149. ...
  150. }
  151. ```
  152. #### <a name="get-data"></a> `> cacache.get(cache, key, [opts]) -> Promise({data, metadata, integrity})`
  153. Returns an object with the cached data, digest, and metadata identified by
  154. `key`. The `data` property of this object will be a `Buffer` instance that
  155. presumably holds some data that means something to you. I'm sure you know what
  156. to do with it! cacache just won't care.
  157. `integrity` is a [Subresource
  158. Integrity](#integrity)
  159. string. That is, a string that can be used to verify `data`, which looks like
  160. `<hash-algorithm>-<base64-integrity-hash>`.
  161. If there is no content identified by `key`, or if the locally-stored data does
  162. not pass the validity checksum, the promise will be rejected.
  163. A sub-function, `get.byDigest` may be used for identical behavior, except lookup
  164. will happen by integrity hash, bypassing the index entirely. This version of the
  165. function *only* returns `data` itself, without any wrapper.
  166. ##### Note
  167. This function loads the entire cache entry into memory before returning it. If
  168. you're dealing with Very Large data, consider using [`get.stream`](#get-stream)
  169. instead.
  170. ##### Example
  171. ```javascript
  172. // Look up by key
  173. cache.get(cachePath, 'my-thing').then(console.log)
  174. // Output:
  175. {
  176. metadata: {
  177. thingName: 'my'
  178. },
  179. integrity: 'sha512-BaSe64HaSh',
  180. data: Buffer#<deadbeef>,
  181. size: 9320
  182. }
  183. // Look up by digest
  184. cache.get.byDigest(cachePath, 'sha512-BaSe64HaSh').then(console.log)
  185. // Output:
  186. Buffer#<deadbeef>
  187. ```
  188. #### <a name="get-stream"></a> `> cacache.get.stream(cache, key, [opts]) -> Readable`
  189. Returns a [Readable Stream](https://nodejs.org/api/stream.html#stream_readable_streams) of the cached data identified by `key`.
  190. If there is no content identified by `key`, or if the locally-stored data does
  191. not pass the validity checksum, an error will be emitted.
  192. `metadata` and `integrity` events will be emitted before the stream closes, if
  193. you need to collect that extra data about the cached entry.
  194. A sub-function, `get.stream.byDigest` may be used for identical behavior,
  195. except lookup will happen by integrity hash, bypassing the index entirely. This
  196. version does not emit the `metadata` and `integrity` events at all.
  197. ##### Example
  198. ```javascript
  199. // Look up by key
  200. cache.get.stream(
  201. cachePath, 'my-thing'
  202. ).on('metadata', metadata => {
  203. console.log('metadata:', metadata)
  204. }).on('integrity', integrity => {
  205. console.log('integrity:', integrity)
  206. }).pipe(
  207. fs.createWriteStream('./x.tgz')
  208. )
  209. // Outputs:
  210. metadata: { ... }
  211. integrity: 'sha512-SoMeDIGest+64=='
  212. // Look up by digest
  213. cache.get.stream.byDigest(
  214. cachePath, 'sha512-SoMeDIGest+64=='
  215. ).pipe(
  216. fs.createWriteStream('./x.tgz')
  217. )
  218. ```
  219. #### <a name="get-info"></a> `> cacache.get.info(cache, key) -> Promise`
  220. Looks up `key` in the cache index, returning information about the entry if
  221. one exists.
  222. ##### Fields
  223. * `key` - Key the entry was looked up under. Matches the `key` argument.
  224. * `integrity` - [Subresource Integrity hash](#integrity) for the content this entry refers to.
  225. * `path` - Filesystem path where content is stored, joined with `cache` argument.
  226. * `time` - Timestamp the entry was first added on.
  227. * `metadata` - User-assigned metadata associated with the entry/content.
  228. ##### Example
  229. ```javascript
  230. cacache.get.info(cachePath, 'my-thing').then(console.log)
  231. // Output
  232. {
  233. key: 'my-thing',
  234. integrity: 'sha256-MUSTVERIFY+ALL/THINGS=='
  235. path: '.testcache/content/deadbeef',
  236. time: 12345698490,
  237. size: 849234,
  238. metadata: {
  239. name: 'blah',
  240. version: '1.2.3',
  241. description: 'this was once a package but now it is my-thing'
  242. }
  243. }
  244. ```
  245. #### <a name="get-hasContent"></a> `> cacache.get.hasContent(cache, integrity) -> Promise`
  246. Looks up a [Subresource Integrity hash](#integrity) in the cache. If content
  247. exists for this `integrity`, it will return an object, with the specific single integrity hash
  248. that was found in `sri` key, and the size of the found content as `size`. If no content exists for this integrity, it will return `false`.
  249. ##### Example
  250. ```javascript
  251. cacache.get.hasContent(cachePath, 'sha256-MUSTVERIFY+ALL/THINGS==').then(console.log)
  252. // Output
  253. {
  254. sri: {
  255. source: 'sha256-MUSTVERIFY+ALL/THINGS==',
  256. algorithm: 'sha256',
  257. digest: 'MUSTVERIFY+ALL/THINGS==',
  258. options: []
  259. },
  260. size: 9001
  261. }
  262. cacache.get.hasContent(cachePath, 'sha521-NOT+IN/CACHE==').then(console.log)
  263. // Output
  264. false
  265. ```
  266. #### <a name="put-data"></a> `> cacache.put(cache, key, data, [opts]) -> Promise`
  267. Inserts data passed to it into the cache. The returned Promise resolves with a
  268. digest (generated according to [`opts.algorithms`](#optsalgorithms)) after the
  269. cache entry has been successfully written.
  270. ##### Example
  271. ```javascript
  272. fetch(
  273. 'https://registry.npmjs.org/cacache/-/cacache-1.0.0.tgz'
  274. ).then(data => {
  275. return cacache.put(cachePath, 'registry.npmjs.org|cacache@1.0.0', data)
  276. }).then(integrity => {
  277. console.log('integrity hash is', integrity)
  278. })
  279. ```
  280. #### <a name="put-stream"></a> `> cacache.put.stream(cache, key, [opts]) -> Writable`
  281. Returns a [Writable
  282. Stream](https://nodejs.org/api/stream.html#stream_writable_streams) that inserts
  283. data written to it into the cache. Emits an `integrity` event with the digest of
  284. written contents when it succeeds.
  285. ##### Example
  286. ```javascript
  287. request.get(
  288. 'https://registry.npmjs.org/cacache/-/cacache-1.0.0.tgz'
  289. ).pipe(
  290. cacache.put.stream(
  291. cachePath, 'registry.npmjs.org|cacache@1.0.0'
  292. ).on('integrity', d => console.log(`integrity digest is ${d}`))
  293. )
  294. ```
  295. #### <a name="put-options"></a> `> cacache.put options`
  296. `cacache.put` functions have a number of options in common.
  297. ##### `opts.metadata`
  298. Arbitrary metadata to be attached to the inserted key.
  299. ##### `opts.size`
  300. If provided, the data stream will be verified to check that enough data was
  301. passed through. If there's more or less data than expected, insertion will fail
  302. with an `EBADSIZE` error.
  303. ##### `opts.integrity`
  304. If present, the pre-calculated digest for the inserted content. If this option
  305. if provided and does not match the post-insertion digest, insertion will fail
  306. with an `EINTEGRITY` error.
  307. `algorithms` has no effect if this option is present.
  308. ##### `opts.algorithms`
  309. Default: ['sha512']
  310. Hashing algorithms to use when calculating the [subresource integrity
  311. digest](#integrity)
  312. for inserted data. Can use any algorithm listed in `crypto.getHashes()` or
  313. `'omakase'`/`'お任せします'` to pick a random hash algorithm on each insertion. You
  314. may also use any anagram of `'modnar'` to use this feature.
  315. Currently only supports one algorithm at a time (i.e., an array length of
  316. exactly `1`). Has no effect if `opts.integrity` is present.
  317. ##### `opts.memoize`
  318. Default: null
  319. If provided, cacache will memoize the given cache insertion in memory, bypassing
  320. any filesystem checks for that key or digest in future cache fetches. Nothing
  321. will be written to the in-memory cache unless this option is explicitly truthy.
  322. If `opts.memoize` is an object or a `Map`-like (that is, an object with `get`
  323. and `set` methods), it will be written to instead of the global memoization
  324. cache.
  325. Reading from disk data can be forced by explicitly passing `memoize: false` to
  326. the reader functions, but their default will be to read from memory.
  327. #### <a name="rm-all"></a> `> cacache.rm.all(cache) -> Promise`
  328. Clears the entire cache. Mainly by blowing away the cache directory itself.
  329. ##### Example
  330. ```javascript
  331. cacache.rm.all(cachePath).then(() => {
  332. console.log('THE APOCALYPSE IS UPON US 😱')
  333. })
  334. ```
  335. #### <a name="rm-entry"></a> `> cacache.rm.entry(cache, key) -> Promise`
  336. Alias: `cacache.rm`
  337. Removes the index entry for `key`. Content will still be accessible if
  338. requested directly by content address ([`get.stream.byDigest`](#get-stream)).
  339. To remove the content itself (which might still be used by other entries), use
  340. [`rm.content`](#rm-content). Or, to safely vacuum any unused content, use
  341. [`verify`](#verify).
  342. ##### Example
  343. ```javascript
  344. cacache.rm.entry(cachePath, 'my-thing').then(() => {
  345. console.log('I did not like it anyway')
  346. })
  347. ```
  348. #### <a name="rm-content"></a> `> cacache.rm.content(cache, integrity) -> Promise`
  349. Removes the content identified by `integrity`. Any index entries referring to it
  350. will not be usable again until the content is re-added to the cache with an
  351. identical digest.
  352. ##### Example
  353. ```javascript
  354. cacache.rm.content(cachePath, 'sha512-SoMeDIGest/IN+BaSE64==').then(() => {
  355. console.log('data for my-thing is gone!')
  356. })
  357. ```
  358. #### <a name="clear-memoized"></a> `> cacache.clearMemoized()`
  359. Completely resets the in-memory entry cache.
  360. #### <a name="tmp-mkdir"></a> `> tmp.mkdir(cache, opts) -> Promise<Path>`
  361. Returns a unique temporary directory inside the cache's `tmp` dir. This
  362. directory will use the same safe user assignment that all the other stuff use.
  363. Once the directory is made, it's the user's responsibility that all files
  364. within are given the appropriate `gid`/`uid` ownership settings to match
  365. the rest of the cache. If not, you can ask cacache to do it for you by
  366. calling [`tmp.fix()`](#tmp-fix), which will fix all tmp directory
  367. permissions.
  368. If you want automatic cleanup of this directory, use
  369. [`tmp.withTmp()`](#with-tpm)
  370. ##### Example
  371. ```javascript
  372. cacache.tmp.mkdir(cache).then(dir => {
  373. fs.writeFile(path.join(dir, 'blablabla'), Buffer#<1234>, ...)
  374. })
  375. ```
  376. #### <a name="tmp-fix"></a> `> tmp.fix(cache) -> Promise`
  377. Sets the `uid` and `gid` properties on all files and folders within the tmp
  378. folder to match the rest of the cache.
  379. Use this after manually writing files into [`tmp.mkdir`](#tmp-mkdir) or
  380. [`tmp.withTmp`](#with-tmp).
  381. ##### Example
  382. ```javascript
  383. cacache.tmp.mkdir(cache).then(dir => {
  384. writeFile(path.join(dir, 'file'), someData).then(() => {
  385. // make sure we didn't just put a root-owned file in the cache
  386. cacache.tmp.fix().then(() => {
  387. // all uids and gids match now
  388. })
  389. })
  390. })
  391. ```
  392. #### <a name="with-tmp"></a> `> tmp.withTmp(cache, opts, cb) -> Promise`
  393. Creates a temporary directory with [`tmp.mkdir()`](#tmp-mkdir) and calls `cb`
  394. with it. The created temporary directory will be removed when the return value
  395. of `cb()` resolves, the tmp directory will be automatically deleted once that
  396. promise completes.
  397. The same caveats apply when it comes to managing permissions for the tmp dir's
  398. contents.
  399. ##### Example
  400. ```javascript
  401. cacache.tmp.withTmp(cache, dir => {
  402. return fs.writeFileAsync(path.join(dir, 'blablabla'), Buffer#<1234>, ...)
  403. }).then(() => {
  404. // `dir` no longer exists
  405. })
  406. ```
  407. #### <a name="integrity"></a> Subresource Integrity Digests
  408. For content verification and addressing, cacache uses strings following the
  409. [Subresource
  410. Integrity spec](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity).
  411. That is, any time cacache expects an `integrity` argument or option, it
  412. should be in the format `<hashAlgorithm>-<base64-hash>`.
  413. One deviation from the current spec is that cacache will support any hash
  414. algorithms supported by the underlying Node.js process. You can use
  415. `crypto.getHashes()` to see which ones you can use.
  416. ##### Generating Digests Yourself
  417. If you have an existing content shasum, they are generally formatted as a
  418. hexadecimal string (that is, a sha1 would look like:
  419. `5f5513f8822fdbe5145af33b64d8d970dcf95c6e`). In order to be compatible with
  420. cacache, you'll need to convert this to an equivalent subresource integrity
  421. string. For this example, the corresponding hash would be:
  422. `sha1-X1UT+IIv2+UUWvM7ZNjZcNz5XG4=`.
  423. If you want to generate an integrity string yourself for existing data, you can
  424. use something like this:
  425. ```javascript
  426. const crypto = require('crypto')
  427. const hashAlgorithm = 'sha512'
  428. const data = 'foobarbaz'
  429. const integrity = (
  430. hashAlgorithm +
  431. '-' +
  432. crypto.createHash(hashAlgorithm).update(data).digest('base64')
  433. )
  434. ```
  435. You can also use [`ssri`](https://npm.im/ssri) to have a richer set of functionality
  436. around SRI strings, including generation, parsing, and translating from existing
  437. hex-formatted strings.
  438. #### <a name="verify"></a> `> cacache.verify(cache, opts) -> Promise`
  439. Checks out and fixes up your cache:
  440. * Cleans up corrupted or invalid index entries.
  441. * Custom entry filtering options.
  442. * Garbage collects any content entries not referenced by the index.
  443. * Checks integrity for all content entries and removes invalid content.
  444. * Fixes cache ownership.
  445. * Removes the `tmp` directory in the cache and all its contents.
  446. When it's done, it'll return an object with various stats about the verification
  447. process, including amount of storage reclaimed, number of valid entries, number
  448. of entries removed, etc.
  449. ##### Options
  450. * `opts.filter` - receives a formatted entry. Return false to remove it.
  451. Note: might be called more than once on the same entry.
  452. ##### Example
  453. ```sh
  454. echo somegarbage >> $CACHEPATH/content/deadbeef
  455. ```
  456. ```javascript
  457. cacache.verify(cachePath).then(stats => {
  458. // deadbeef collected, because of invalid checksum.
  459. console.log('cache is much nicer now! stats:', stats)
  460. })
  461. ```
  462. #### <a name="verify-last-run"></a> `> cacache.verify.lastRun(cache) -> Promise`
  463. Returns a `Date` representing the last time `cacache.verify` was run on `cache`.
  464. ##### Example
  465. ```javascript
  466. cacache.verify(cachePath).then(() => {
  467. cacache.verify.lastRun(cachePath).then(lastTime => {
  468. console.log('cacache.verify was last called on' + lastTime)
  469. })
  470. })
  471. ```