Skip to content
This repository was archived by the owner on Dec 1, 2024. It is now read-only.

Commit e1ecad9

Browse files
authored
Document new features (#727)
- Add `for await...of` example - Remove notice that `db.supports` isn't (wasn't) widely supported - Remove notice that `db.clear()` is (was) experimental - Simplify Promise Support section - Document `status` in preference over `isXX()` utilities - Remove redundant API table of contents
1 parent 7bc86e4 commit e1ecad9

File tree

2 files changed

+39
-129
lines changed

2 files changed

+39
-129
lines changed

README.md

Lines changed: 37 additions & 119 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
- [Supported Platforms](#supported-platforms)
1818
- [Usage](#usage)
1919
- [API](#api)
20-
- [Special Notes](#special-notes)
2120
- [`levelup(db[, options[, callback]])`](#levelupdb-options-callback)
2221
- [`db.supports`](#dbsupports)
2322
- [`db.open([options][, callback])`](#dbopenoptions-callback)
@@ -28,14 +27,14 @@
2827
- [`db.del(key[, options][, callback])`](#dbdelkey-options-callback)
2928
- [`db.batch(array[, options][, callback])` _(array form)_](#dbbatcharray-options-callback-array-form)
3029
- [`db.batch()` _(chained form)_](#dbbatch-chained-form)
31-
- [`db.isOpen()`](#dbisopen)
32-
- [`db.isClosed()`](#dbisclosed)
30+
- [`db.status`](#dbstatus)
31+
- [`db.isOperational()`](#dbisoperational)
3332
- [`db.createReadStream([options])`](#dbcreatereadstreamoptions)
3433
- [`db.createKeyStream([options])`](#dbcreatekeystreamoptions)
3534
- [`db.createValueStream([options])`](#dbcreatevaluestreamoptions)
3635
- [`db.iterator([options])`](#dbiteratoroptions)
3736
- [`db.clear([options][, callback])`](#dbclearoptions-callback)
38-
- [What happened to `db.createWriteStream`?](#what-happened-to-dbcreatewritestream)
37+
- [What happened to `db.createWriteStream`?](#what-happened-to-dbcreatewritestream)
3938
- [Promise Support](#promise-support)
4039
- [Events](#events)
4140
- [Multi-process Access](#multi-process-access)
@@ -52,7 +51,7 @@
5251

5352
LevelDB is a simple key-value store built by Google. It's used in Google Chrome and many other products. LevelDB supports arbitrary byte arrays as both keys and values, singular _get_, _put_ and _delete_ operations, _batched put and delete_, bi-directional iterators and simple compression using the very fast [Snappy](http://google.github.io/snappy/) algorithm.
5453

55-
LevelDB stores entries sorted lexicographically by keys. This makes the <a href="#createReadStream">streaming interface</a> of `levelup` - which exposes LevelDB iterators as [Readable Streams](https://nodejs.org/docs/latest/api/stream.html#stream_readable_streams) - a very powerful query mechanism.
54+
LevelDB stores entries sorted lexicographically by keys. This makes the streaming interface of `levelup` - which exposes LevelDB iterators as [Readable Streams](https://nodejs.org/docs/latest/api/stream.html#stream_readable_streams) - a very powerful query mechanism.
5655

5756
The most common store is [`leveldown`](https://github.com/Level/leveldown/) which provides a pure C++ binding to LevelDB. [Many alternative stores are available](https://github.com/Level/awesome/#stores) such as [`level.js`](https://github.com/Level/level.js) in the browser or [`memdown`](https://github.com/Level/memdown) for an in-memory store. They typically support strings and Buffers for both keys and values. For a richer set of data types you can wrap the store with [`encoding-down`](https://github.com/Level/encoding-down).
5857

@@ -66,7 +65,7 @@ We aim to support Active LTS and Current Node.js releases as well as browsers. F
6665

6766
## Usage
6867

69-
**If you are upgrading:** please see [`UPGRADING.md`](UPGRADING.md).
68+
_If you are upgrading: please see [`UPGRADING.md`](UPGRADING.md)._
7069

7170
First you need to install `levelup`! No stores are included so you must also install `leveldown` (for example).
7271

@@ -99,29 +98,6 @@ db.put('name', 'levelup', function (err) {
9998

10099
## API
101100

102-
- <a href="#ctor"><code><b>levelup()</b></code></a>
103-
- <a href="#supports"><code>db.<b>supports</b></code></a>
104-
- <a href="#open"><code>db.<b>open()</b></code></a>
105-
- <a href="#close"><code>db.<b>close()</b></code></a>
106-
- <a href="#put"><code>db.<b>put()</b></code></a>
107-
- <a href="#get"><code>db.<b>get()</b></code></a>
108-
- <a href="#del"><code>db.<b>del()</b></code></a>
109-
- <a href="#batch"><code>db.<b>batch()</b></code></a> _(array form)_
110-
- <a href="#batch_chained"><code>db.<b>batch()</b></code></a> _(chained form)_
111-
- <a href="#isOpen"><code>db.<b>isOpen()</b></code></a>
112-
- <a href="#isClosed"><code>db.<b>isClosed()</b></code></a>
113-
- <a href="#createReadStream"><code>db.<b>createReadStream()</b></code></a>
114-
- <a href="#createKeyStream"><code>db.<b>createKeyStream()</b></code></a>
115-
- <a href="#createValueStream"><code>db.<b>createValueStream()</b></code></a>
116-
- <a href="#iterator"><code>db.<b>iterator()</b></code></a>
117-
- <a href="#clear"><code>db.<b>clear()</b></code></a>
118-
119-
### Special Notes
120-
121-
- <a href="#writeStreams">What happened to <code><b>db.createWriteStream()</b></code></a>
122-
123-
<a name="ctor"></a>
124-
125101
### `levelup(db[, options[, callback]])`
126102

127103
The main entry point for creating a new `levelup` instance.
@@ -156,11 +132,9 @@ db.get('foo', function (err, value) {
156132
})
157133
```
158134

159-
<a name="supports"></a>
160-
161135
### `db.supports`
162136

163-
A read-only [manifest](https://github.com/Level/supports). Not [widely supported yet](https://github.com/Level/community/issues/83). Might be used like so:
137+
A read-only [manifest](https://github.com/Level/supports). Might be used like so:
164138

165139
```js
166140
if (!db.supports.permanence) {
@@ -172,38 +146,28 @@ if (db.supports.bufferKeys && db.supports.promises) {
172146
}
173147
```
174148

175-
<a name="open"></a>
176-
177149
### `db.open([options][, callback])`
178150

179-
Opens the underlying store. In general you should never need to call this method directly as it's automatically called by <a href="#ctor"><code>levelup()</code></a>.
180-
181-
However, it is possible to _reopen_ the store after it has been closed with <a href="#close"><code>close()</code></a>, although this is not generally advised.
151+
Opens the underlying store. In general you shouldn't need to call this method directly as it's automatically called by [`levelup()`](#levelupdb-options-callback). However, it is possible to reopen the store after it has been closed with [`close()`](#dbclosecallback).
182152

183153
If no callback is passed, a promise is returned.
184154

185-
<a name="close"></a>
186-
187155
### `db.close([callback])`
188156

189-
<code>close()</code> closes the underlying store. The callback will receive any error encountered during closing as the first argument.
157+
`close()` closes the underlying store. The callback will receive any error encountered during closing as the first argument.
190158

191159
You should always clean up your `levelup` instance by calling `close()` when you no longer need it to free up resources. A store cannot be opened by multiple instances of `levelup` simultaneously.
192160

193161
If no callback is passed, a promise is returned.
194162

195-
<a name="put"></a>
196-
197163
### `db.put(key, value[, options][, callback])`
198164

199-
<code>put()</code> is the primary method for inserting data into the store. Both `key` and `value` can be of any type as far as `levelup` is concerned.
165+
`put()` is the primary method for inserting data into the store. Both `key` and `value` can be of any type as far as `levelup` is concerned.
200166

201167
`options` is passed on to the underlying store.
202168

203169
If no callback is passed, a promise is returned.
204170

205-
<a name="get"></a>
206-
207171
### `db.get(key[, options][, callback])`
208172

209173
Get a value from the store by `key`. The `key` can be of any type. If it doesn't exist in the store then the callback or promise will receive an error. A not-found err object will be of type `'NotFoundError'` so you can `err.type == 'NotFoundError'` or you can perform a truthy test on the property `err.notFound`.
@@ -227,8 +191,6 @@ The optional `options` object is passed on to the underlying store.
227191

228192
If no callback is passed, a promise is returned.
229193

230-
<a name="get_many"></a>
231-
232194
### `db.getMany(keys[, options][, callback])`
233195

234196
Get multiple values from the store by an array of `keys`. The optional `options` object is passed on to the underlying store.
@@ -237,11 +199,9 @@ The `callback` function will be called with an `Error` if the operation failed f
237199

238200
If no callback is provided, a promise is returned.
239201

240-
<a name="del"></a>
241-
242202
### `db.del(key[, options][, callback])`
243203

244-
<code>del()</code> is the primary method for removing data from the store.
204+
`del()` is the primary method for removing data from the store.
245205

246206
```js
247207
db.del('foo', function (err) {
@@ -254,16 +214,14 @@ db.del('foo', function (err) {
254214

255215
If no callback is passed, a promise is returned.
256216

257-
<a name="batch"></a>
258-
259217
### `db.batch(array[, options][, callback])` _(array form)_
260218

261-
<code>batch()</code> can be used for very fast bulk-write operations (both _put_ and _delete_). The `array` argument should contain a list of operations to be executed sequentially, although as a whole they are performed as an atomic operation inside the underlying store.
219+
`batch()` can be used for very fast bulk-write operations (both _put_ and _delete_). The `array` argument should contain a list of operations to be executed sequentially, although as a whole they are performed as an atomic operation inside the underlying store.
262220

263221
Each operation is contained in an object having the following properties: `type`, `key`, `value`, where the _type_ is either `'put'` or `'del'`. In the case of `'del'` the `value` property is ignored. Any entries with a `key` of `null` or `undefined` will cause an error to be returned on the `callback` and any `type: 'put'` entry with a `value` of `null` or `undefined` will return an error.
264222

265223
```js
266-
var ops = [
224+
const ops = [
267225
{ type: 'del', key: 'father' },
268226
{ type: 'put', key: 'name', value: 'Yuri Irsenovich Kim' },
269227
{ type: 'put', key: 'dob', value: '16 February 1941' },
@@ -281,11 +239,9 @@ db.batch(ops, function (err) {
281239

282240
If no callback is passed, a promise is returned.
283241

284-
<a name="batch_chained"></a>
285-
286242
### `db.batch()` _(chained form)_
287243

288-
<code>batch()</code>, when called with no arguments will return a `Batch` object which can be used to build, and eventually commit, an atomic batch operation. Depending on how it's used, it is possible to obtain greater performance when using the chained form of `batch()` over the array form.
244+
`batch()`, when called with no arguments will return a `Batch` object which can be used to build, and eventually commit, an atomic batch operation. Depending on how it's used, it is possible to obtain greater performance when using the chained form of `batch()` over the array form.
289245

290246
```js
291247
db.batch()
@@ -325,29 +281,19 @@ The optional `options` object is passed to the `.write()` operation of the under
325281

326282
If no callback is passed, a promise is returned.
327283

328-
<a name="isOpen"></a>
329-
330-
### `db.isOpen()`
331-
332-
A `levelup` instance can be in one of the following states:
333-
334-
- _"new"_ - newly created, not opened or closed
335-
- _"opening"_ - waiting for the underlying store to be opened
336-
- _"open"_ - successfully opened the store, available for use
337-
- _"closing"_ - waiting for the store to be closed
338-
- _"closed"_ - store has been successfully closed, should not be used
284+
### `db.status`
339285

340-
`isOpen()` will return `true` only when the state is "open".
286+
A readonly string that is one of:
341287

342-
<a name="isClosed"></a>
288+
- `new` - newly created, not opened or closed
289+
- `opening` - waiting for the underlying store to be opened
290+
- `open` - successfully opened the store, available for use
291+
- `closing` - waiting for the store to be closed
292+
- `closed` - store has been successfully closed.
343293

344-
### `db.isClosed()`
294+
### `db.isOperational()`
345295

346-
_See <a href="#put"><code>isOpen()</code></a>_
347-
348-
`isClosed()` will return `true` only when the state is "closing" _or_ "closed", it can be useful for determining if read and write operations are permissible.
349-
350-
<a name="createReadStream"></a>
296+
Returns `true` if the store accepts operations, which in the case of `levelup` means that `status` is either `opening` or `open`, because it opens itself and queues up operations until opened.
351297

352298
### `db.createReadStream([options])`
353299

@@ -383,11 +329,9 @@ You can supply an options object as the first parameter to `createReadStream()`
383329

384330
- `values` _(boolean, default: `true`)_: whether the results should contain values. If set to `true` and `keys` set to `false` then results will simply be values, rather than objects with a `value` property. Used internally by the `createValueStream()` method.
385331

386-
<a name="createKeyStream"></a>
387-
388332
### `db.createKeyStream([options])`
389333

390-
Returns a [Readable Stream](https://nodejs.org/docs/latest/api/stream.html#stream_readable_streams) of keys rather than key-value pairs. Use the same options as described for <a href="#createReadStream"><code>createReadStream</code></a> to control the range and direction.
334+
Returns a [Readable Stream](https://nodejs.org/docs/latest/api/stream.html#stream_readable_streams) of keys rather than key-value pairs. Use the same options as described for [`createReadStream()`](#dbcreatereadstreamoptions) to control the range and direction.
391335

392336
You can also obtain this stream by passing an options object to `createReadStream()` with `keys` set to `true` and `values` set to `false`. The result is equivalent; both streams operate in [object mode](https://nodejs.org/docs/latest/api/stream.html#stream_object_mode).
393337

@@ -404,11 +348,9 @@ db.createReadStream({ keys: true, values: false })
404348
})
405349
```
406350

407-
<a name="createValueStream"></a>
408-
409351
### `db.createValueStream([options])`
410352

411-
Returns a [Readable Stream](https://nodejs.org/docs/latest/api/stream.html#stream_readable_streams) of values rather than key-value pairs. Use the same options as described for <a href="#createReadStream"><code>createReadStream</code></a> to control the range and direction.
353+
Returns a [Readable Stream](https://nodejs.org/docs/latest/api/stream.html#stream_readable_streams) of values rather than key-value pairs. Use the same options as described for [`createReadStream()`](#dbcreatereadstreamoptions) to control the range and direction.
412354

413355
You can also obtain this stream by passing an options object to `createReadStream()` with `values` set to `true` and `keys` set to `false`. The result is equivalent; both streams operate in [object mode](https://nodejs.org/docs/latest/api/stream.html#stream_object_mode).
414356

@@ -425,17 +367,19 @@ db.createReadStream({ keys: false, values: true })
425367
})
426368
```
427369

428-
<a name="iterator"></a>
429-
430370
### `db.iterator([options])`
431371

432-
Returns an [`abstract-leveldown` iterator](https://github.com/Level/abstract-leveldown/#abstractleveldown_iteratoroptions), which is what powers the readable streams above. Options are the same as the range options of <a href="#createReadStream"><code>createReadStream</code></a> and are passed to the underlying store.
372+
Returns an [`abstract-leveldown` iterator](https://github.com/Level/abstract-leveldown/#abstractleveldown_iteratoroptions), which is what powers the readable streams above. Options are the same as the range options of [`createReadStream()`](#dbcreatereadstreamoptions) and are passed to the underlying store.
433373

434-
<a name="clear"></a>
374+
These iterators support [`for await...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of):
435375

436-
### `db.clear([options][, callback])`
376+
```js
377+
for await (const [key, value] of db.iterator()) {
378+
console.log(value)
379+
}
380+
```
437381

438-
**This method is experimental. Not all underlying stores support it yet. Consult [Level/community#79](https://github.com/Level/community/issues/79) to find out if your (combination of) dependencies support `db.clear()`.**
382+
### `db.clear([options][, callback])`
439383

440384
Delete all entries or a range. Not guaranteed to be atomic. Accepts the following range options (with the same rules as on iterators):
441385

@@ -448,9 +392,7 @@ If no options are provided, all entries will be deleted. The `callback` function
448392

449393
If no callback is passed, a promise is returned.
450394

451-
<a name="writeStreams"></a>
452-
453-
#### What happened to `db.createWriteStream`?
395+
## What happened to `db.createWriteStream`?
454396

455397
`db.createWriteStream()` has been removed in order to provide a smaller and more maintainable core. It primarily existed to create symmetry with `db.createReadStream()` but through much [discussion](https://github.com/Level/levelup/issues/199), removing it was the best course of action.
456398

@@ -460,38 +402,14 @@ Check out the implementations that the community has produced [here](https://git
460402

461403
## Promise Support
462404

463-
`levelup` ships with native `Promise` support out of the box.
464-
465-
Each function accepting a callback returns a promise if the callback is omitted. This applies for:
466-
467-
- `db.get(key[, options])`
468-
- `db.put(key, value[, options])`
469-
- `db.del(key[, options])`
470-
- `db.batch(ops[, options])`
471-
- `db.batch().write()`
472-
473-
The only exception is the `levelup` constructor itself, which if no callback is passed will lazily open the underlying store in the background.
405+
Each function accepting a callback returns a promise if the callback is omitted. The only exception is the `levelup` constructor itself, which if no callback is passed will lazily open the underlying store in the background.
474406

475407
Example:
476408

477409
```js
478-
var db = levelup(leveldown('./my-db'))
479-
480-
db.put('foo', 'bar')
481-
.then(function () { return db.get('foo') })
482-
.then(function (value) { console.log(value) })
483-
.catch(function (err) { console.error(err) })
484-
```
485-
486-
Or using `async/await`:
487-
488-
```js
489-
const main = async () => {
490-
const db = levelup(leveldown('./my-db'))
491-
492-
await db.put('foo', 'bar')
493-
console.log(await db.get('foo'))
494-
}
410+
const db = levelup(leveldown('./my-db'))
411+
await db.put('foo', 'bar')
412+
console.log(await db.get('foo'))
495413
```
496414

497415
## Events

lib/levelup.js

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,6 @@ const NotFoundError = errors.NotFoundError
2020
const OpenError = errors.OpenError
2121
const InitializationError = errors.InitializationError
2222

23-
// Possible AbstractLevelDOWN#status values:
24-
// - 'new' - newly created, not opened or closed
25-
// - 'opening' - waiting for the database to be opened, post open()
26-
// - 'open' - successfully opened the database, available for use
27-
// - 'closing' - waiting for the database to be closed, post close()
28-
// - 'closed' - database has been successfully closed, should not be
29-
// used except for another open() operation
30-
3123
function LevelUP (db, options, callback) {
3224
if (!(this instanceof LevelUP)) {
3325
return new LevelUP(db, options, callback)
@@ -88,15 +80,15 @@ LevelUP.prototype.emit = EventEmitter.prototype.emit
8880
LevelUP.prototype.once = EventEmitter.prototype.once
8981
inherits(LevelUP, EventEmitter)
9082

91-
// TODO: docs and tests
83+
// TODO: tests
9284
Object.defineProperty(LevelUP.prototype, 'status', {
9385
enumerable: true,
9486
get () {
9587
return this.db.status
9688
}
9789
})
9890

99-
// TODO: docs and tests
91+
// TODO: tests
10092
LevelUP.prototype.isOperational = function () {
10193
return this.db.status === 'open' || this.db.status === 'opening'
10294
}

0 commit comments

Comments
 (0)