diff --git a/README.md b/README.md index ec74f288..fb6e3299 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,6 @@ - [Supported Platforms](#supported-platforms) - [Usage](#usage) - [API](#api) - - [Special Notes](#special-notes) - [`levelup(db[, options[, callback]])`](#levelupdb-options-callback) - [`db.supports`](#dbsupports) - [`db.open([options][, callback])`](#dbopenoptions-callback) @@ -28,14 +27,14 @@ - [`db.del(key[, options][, callback])`](#dbdelkey-options-callback) - [`db.batch(array[, options][, callback])` _(array form)_](#dbbatcharray-options-callback-array-form) - [`db.batch()` _(chained form)_](#dbbatch-chained-form) - - [`db.isOpen()`](#dbisopen) - - [`db.isClosed()`](#dbisclosed) + - [`db.status`](#dbstatus) + - [`db.isOperational()`](#dbisoperational) - [`db.createReadStream([options])`](#dbcreatereadstreamoptions) - [`db.createKeyStream([options])`](#dbcreatekeystreamoptions) - [`db.createValueStream([options])`](#dbcreatevaluestreamoptions) - [`db.iterator([options])`](#dbiteratoroptions) - [`db.clear([options][, callback])`](#dbclearoptions-callback) - - [What happened to `db.createWriteStream`?](#what-happened-to-dbcreatewritestream) +- [What happened to `db.createWriteStream`?](#what-happened-to-dbcreatewritestream) - [Promise Support](#promise-support) - [Events](#events) - [Multi-process Access](#multi-process-access) @@ -52,7 +51,7 @@ 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. -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. +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. 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). @@ -66,7 +65,7 @@ We aim to support Active LTS and Current Node.js releases as well as browsers. F ## Usage -**If you are upgrading:** please see [`UPGRADING.md`](UPGRADING.md). +_If you are upgrading: please see [`UPGRADING.md`](UPGRADING.md)._ First you need to install `levelup`! No stores are included so you must also install `leveldown` (for example). @@ -99,29 +98,6 @@ db.put('name', 'levelup', function (err) { ## API -- levelup() -- db.supports -- db.open() -- db.close() -- db.put() -- db.get() -- db.del() -- db.batch() _(array form)_ -- db.batch() _(chained form)_ -- db.isOpen() -- db.isClosed() -- db.createReadStream() -- db.createKeyStream() -- db.createValueStream() -- db.iterator() -- db.clear() - -### Special Notes - -- What happened to db.createWriteStream() - - - ### `levelup(db[, options[, callback]])` The main entry point for creating a new `levelup` instance. @@ -156,11 +132,9 @@ db.get('foo', function (err, value) { }) ``` - - ### `db.supports` -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: +A read-only [manifest](https://github.com/Level/supports). Might be used like so: ```js if (!db.supports.permanence) { @@ -172,38 +146,28 @@ if (db.supports.bufferKeys && db.supports.promises) { } ``` - - ### `db.open([options][, callback])` -Opens the underlying store. In general you should never need to call this method directly as it's automatically called by levelup(). - -However, it is possible to _reopen_ the store after it has been closed with close(), although this is not generally advised. +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). If no callback is passed, a promise is returned. - - ### `db.close([callback])` -close() closes the underlying store. The callback will receive any error encountered during closing as the first argument. +`close()` closes the underlying store. The callback will receive any error encountered during closing as the first argument. 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. If no callback is passed, a promise is returned. - - ### `db.put(key, value[, options][, callback])` -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. +`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. `options` is passed on to the underlying store. If no callback is passed, a promise is returned. - - ### `db.get(key[, options][, callback])` 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. If no callback is passed, a promise is returned. - - ### `db.getMany(keys[, options][, callback])` 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 If no callback is provided, a promise is returned. - - ### `db.del(key[, options][, callback])` -del() is the primary method for removing data from the store. +`del()` is the primary method for removing data from the store. ```js db.del('foo', function (err) { @@ -254,16 +214,14 @@ db.del('foo', function (err) { If no callback is passed, a promise is returned. - - ### `db.batch(array[, options][, callback])` _(array form)_ -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. +`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. 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. ```js -var ops = [ +const ops = [ { type: 'del', key: 'father' }, { type: 'put', key: 'name', value: 'Yuri Irsenovich Kim' }, { type: 'put', key: 'dob', value: '16 February 1941' }, @@ -281,11 +239,9 @@ db.batch(ops, function (err) { If no callback is passed, a promise is returned. - - ### `db.batch()` _(chained form)_ -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. +`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. ```js db.batch() @@ -325,29 +281,19 @@ The optional `options` object is passed to the `.write()` operation of the under If no callback is passed, a promise is returned. - - -### `db.isOpen()` - -A `levelup` instance can be in one of the following states: - -- _"new"_ - newly created, not opened or closed -- _"opening"_ - waiting for the underlying store to be opened -- _"open"_ - successfully opened the store, available for use -- _"closing"_ - waiting for the store to be closed -- _"closed"_ - store has been successfully closed, should not be used +### `db.status` -`isOpen()` will return `true` only when the state is "open". +A readonly string that is one of: - +- `new` - newly created, not opened or closed +- `opening` - waiting for the underlying store to be opened +- `open` - successfully opened the store, available for use +- `closing` - waiting for the store to be closed +- `closed` - store has been successfully closed. -### `db.isClosed()` +### `db.isOperational()` -_See isOpen()_ - -`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. - - +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. ### `db.createReadStream([options])` @@ -383,11 +329,9 @@ You can supply an options object as the first parameter to `createReadStream()` - `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. - - ### `db.createKeyStream([options])` -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 to control the range and direction. +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. 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). @@ -404,11 +348,9 @@ db.createReadStream({ keys: true, values: false }) }) ``` - - ### `db.createValueStream([options])` -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 to control the range and direction. +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. 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). @@ -425,17 +367,19 @@ db.createReadStream({ keys: false, values: true }) }) ``` - - ### `db.iterator([options])` -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 and are passed to the underlying store. +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. - +These iterators support [`for await...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of): -### `db.clear([options][, callback])` +```js +for await (const [key, value] of db.iterator()) { + console.log(value) +} +``` -**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()`.** +### `db.clear([options][, callback])` Delete all entries or a range. Not guaranteed to be atomic. Accepts the following range options (with the same rules as on iterators): @@ -448,9 +392,7 @@ If no options are provided, all entries will be deleted. The `callback` function If no callback is passed, a promise is returned. - - -#### What happened to `db.createWriteStream`? +## What happened to `db.createWriteStream`? `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. @@ -460,38 +402,14 @@ Check out the implementations that the community has produced [here](https://git ## Promise Support -`levelup` ships with native `Promise` support out of the box. - -Each function accepting a callback returns a promise if the callback is omitted. This applies for: - -- `db.get(key[, options])` -- `db.put(key, value[, options])` -- `db.del(key[, options])` -- `db.batch(ops[, options])` -- `db.batch().write()` - -The only exception is the `levelup` constructor itself, which if no callback is passed will lazily open the underlying store in the background. +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. Example: ```js -var db = levelup(leveldown('./my-db')) - -db.put('foo', 'bar') - .then(function () { return db.get('foo') }) - .then(function (value) { console.log(value) }) - .catch(function (err) { console.error(err) }) -``` - -Or using `async/await`: - -```js -const main = async () => { - const db = levelup(leveldown('./my-db')) - - await db.put('foo', 'bar') - console.log(await db.get('foo')) -} +const db = levelup(leveldown('./my-db')) +await db.put('foo', 'bar') +console.log(await db.get('foo')) ``` ## Events diff --git a/lib/levelup.js b/lib/levelup.js index 3a6add4d..ed61faa4 100644 --- a/lib/levelup.js +++ b/lib/levelup.js @@ -20,14 +20,6 @@ const NotFoundError = errors.NotFoundError const OpenError = errors.OpenError const InitializationError = errors.InitializationError -// Possible AbstractLevelDOWN#status values: -// - 'new' - newly created, not opened or closed -// - 'opening' - waiting for the database to be opened, post open() -// - 'open' - successfully opened the database, available for use -// - 'closing' - waiting for the database to be closed, post close() -// - 'closed' - database has been successfully closed, should not be -// used except for another open() operation - function LevelUP (db, options, callback) { if (!(this instanceof LevelUP)) { return new LevelUP(db, options, callback) @@ -88,7 +80,7 @@ LevelUP.prototype.emit = EventEmitter.prototype.emit LevelUP.prototype.once = EventEmitter.prototype.once inherits(LevelUP, EventEmitter) -// TODO: docs and tests +// TODO: tests Object.defineProperty(LevelUP.prototype, 'status', { enumerable: true, get () { @@ -96,7 +88,7 @@ Object.defineProperty(LevelUP.prototype, 'status', { } }) -// TODO: docs and tests +// TODO: tests LevelUP.prototype.isOperational = function () { return this.db.status === 'open' || this.db.status === 'opening' }