1. 程式人生 > >Level/levelup-2-API

Level/levelup-2-API

https://github.com/Level/levelup

 

Special Notes

levelup(db[, options[, callback]])

The main entry point for creating a new levelup instance.

建立新的levelup例項的主要入口

  • db must be an abstract-leveldown compliant store. db必須是抽象leveldown相容儲存器
  • options is passed on to the underlying store when opened and is specific to the type of store being used 在開啟時options值被傳遞給其下面的儲存器,並且指定被使用的儲存器的型別

Calling levelup(db) will also open the underlying store. This is an asynchronous operation which will trigger your callback if you provide one. The callback should take the form function (err, db) {}

 where db is the levelup instance. If you don't provide a callback, any read & write operations are simply queued internally until the store is fully opened.

呼叫levelup(db)也將會開啟底層儲存器。這是個非同步操作,如果你提供了回撥函式將會被觸發。這個回撥將使用function (err, db) {}格式,db即levelup例項。如果你沒有提供回撥函式,任何讀寫操作將僅進行簡單內部排序,直至儲存器完全開啟

This leads to two alternative ways of managing a levelup instance:

這將導致兩種可選的處理levelup例項的方法:

levelup(leveldown(location), options, function (err, db) {
  if (err) throw err

  db.get('foo', function (err, value) {
    if (err) return console.log('foo does not exist')
    console.log('got foo =', value)
  })
})

Versus the equivalent:

與之相等的是:

// Will throw if an error occurs
var db = levelup(leveldown(location), options)

db.get('foo', function (err, value) {
  if (err) return console.log('foo does not exist')
  console.log('got foo =', value)
})

 

 

db.open([callback])

Opens the underlying store. In general you should never need to call this method directly as it's automatically called by levelup().

開啟底層的儲存器。通常來說,你應該不需要直接呼叫這個方法,因為它會自動被levelup()函式呼叫

However, it is possible to reopen the store after it has been closed with close(), although this is not generally advised.

可是,在被close()函式關閉後還是可以使用這個重啟儲存器的,雖然通常是不推薦使用的

If no callback is passed, a promise is returned.

如果沒有傳遞迴調函式,將返回promise

 

 

db.close([callback])

close() closes the underlying store. The callback will receive any error encountered during closing as the first argument.

close()函式將關閉底層儲存器。這個回撥函式將收到在關閉時任何遇見的錯誤,並將其作為第一個引數

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.

在你不在需要levelup例項去釋放資源時,你應該總是要通過呼叫 close()函式來清理它

If no callback is passed, a promise is returned.

如果沒有傳遞迴調函式,將返回promise

 

 

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()函式是主要的插入資料到儲存器的方法。keyvalue可為任意levelup包含的型別

options is passed on to the underlying store.

options值將會傳遞給底層的儲存器

If no callback is passed, a promise is returned.

如果沒有傳遞迴調函式,將返回promise

 

 

db.get(key[, options][, callback])

get() is the primary method for fetching data from the store. 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.

get()函式是主要的從儲存器中獲取資料的方法。key值可以是任意型別。如果它不存在於儲存器中,那麼回撥函式或promise將收到error。一個沒有找到的錯誤將被定義為'NotFoundError'方法,所以你可以err.type == 'NotFoundError'或在屬性err.notFound中執行一個可信的測試,如下

db.get('foo', function (err, value) {
  if (err) {
    if (err.notFound) {
      // handle a 'NotFoundError' here
      return
    }
    // I/O or other error, pass it up the callback chain
    return callback(err)
  }

  // .. handle `value` here
})

options is passed on to the underlying store.

options值將會傳遞給底層的儲存器

If no callback is passed, a promise is returned.

如果沒有傳遞迴調函式,將返回promise

 

 

db.del(key[, options][, callback])

del() is the primary method for removing data from the store.

del()是主要的從儲存器中移除資料的方法

db.del('foo', function (err) {
  if (err)
    // handle I/O or other error
});

options is passed on to the underlying store.

options值將會傳遞給底層的儲存器

If no callback is passed, a promise is returned.

如果沒有傳遞迴調函式,將返回promise

 

 

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.

為了快速進行塊寫操作(如 putdelete操作),可以使用batch()函式。array引數應該包含順序執行的操作序列,雖然在底層的儲存器中他們被當作一個整體,即一個原子操作來執行

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.

每一個被包含在物件中的操作都有這如下屬性:type, key, valuetype要麼是put,要麼是del。在del的情況下,value將會被忽略。任何帶著key為null或undefined的條目將導致在callback函式中返回一個錯誤。而任何帶著value為null或undefined的條目的type為put的操作將返回一個錯誤

var ops = [
  { type: 'del', key: 'father' },
  { type: 'put', key: 'name', value: 'Yuri Irsenovich Kim' },
  { type: 'put', key: 'dob', value: '16 February 1941' },
  { type: 'put', key: 'spouse', value: 'Kim Young-sook' },
  { type: 'put', key: 'occupation', value: 'Clown' }
]

db.batch(ops, function (err) {//即進行批處理
  if (err) return console.log('Ooops!', err)
  console.log('Great success dear leader!')
})

options is passed on to the underlying store.

options值將會傳遞給底層的儲存器

If no callback is passed, a promise is returned.

如果沒有傳遞迴調函式,將返回promise

 

 

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()函式當不帶著引數呼叫時將返回一個用於構建的Batch物件,並且最後將提交一個原子批處理操作。當使用batch()的連結形式來覆蓋其陣列格式時,獲取更高的效能是有可能的,這將取決於它是怎麼使用的

db.batch()
  .del('father')
  .put('name', 'Yuri Irsenovich Kim')
  .put('dob', '16 February 1941')
  .put('spouse', 'Kim Young-sook')
  .put('occupation', 'Clown')
  .write(function () { console.log('Done!') })
 

batch.put(key, value)

Queue a put operation on the current batch, not committed until a write() is called on the batch.

在當前的batch物件下排序一個put操作,不提交,直至write()函式被呼叫

This method may throw a WriteError if there is a problem with your put (such as the value being null or undefined).

如果這裡帶著put函式的問題(如value值為null或undefined),這個方法將丟擲一個WriteError

 

batch.del(key)

Queue a del operation on the current batch, not committed until a write() is called on the batch.

在當前的batch物件下排序一個del操作,不提交,直至write()函式被呼叫

This method may throw a WriteError if there is a problem with your delete.

如果這裡帶著delete操作的問題,這個方法將丟擲一個WriteError

 

batch.clear()

Clear all queued operations on the current batch, any previous operations will be discarded.

在當前的batch物件下清理所有排序操作,任何以前的操作將被拋棄

 

batch.length

The number of queued operations on the current batch.

在當前的batch物件下排序的運算元目

 

batch.write([options][, callback])

Commit the queued operations for this batch. All operations not cleared will be written to the underlying store atomically, that is, they will either all succeed or fail with no partial commits.

提交batch物件中排序的操作。所有沒有沒清除的操作將會被自動寫到底層的儲存器中,這個操作要麼全部成功要麼是沒有部分提交的失敗

The optional options object is passed to the .write() operation of the underlying batch object.

可選的options物件被傳遞給底層的batch物件的.write()操作

If no callback is passed, a promise is returned.

如果沒有傳遞迴調函式,將返回promise

 

db.isOpen()

A levelup instance can be in one of the following states:

levelup例項可能是如下的幾種狀態之一:

  • "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 儲存器被成功關閉,不應該被使用

isOpen() will return true only when the state is "open".

isOpen()函式將只在狀態為"open"時返回true

 

 

db.isClosed()

See isOpen() 有關狀態的說法看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.

isClosed()函式將只在狀態為 "closing""closed"時返回true,它可以被用於決定是否讀寫操作被允許

 

 

db.createReadStream([options])

Returns a Readable Stream of key-value pairs. A pair is an object with key and value properties. By default it will stream all entries in the underlying store from start to end. Use the options described below to control the range, direction and results.

返回一個鍵值對的可讀流。一對是一個帶著key和value屬性的物件。預設情況下,它將從頭到尾流遍底層儲存中的所有條目。使用下面描述的options去控制範圍、方向和結果。

db.createReadStream()
  .on('data', function (data) {
    console.log(data.key, '=', data.value)
  })
  .on('error', function (err) {
    console.log('Oh my!', err)
  })
  .on('close', function () {
    console.log('Stream closed')
  })
  .on('end', function () {
    console.log('Stream ended')
  })

You can supply an options object as the first parameter to createReadStream() with the following properties:

你可以使用任何帶著下面的屬性的options物件作為createReadStream()函式的第一個引數

  • gt (greater than), gte (greater than or equal) define the lower bound of the range to be streamed. Only entries where the key is greater than (or equal to) this option will be included in the range. When reverse=true the order will be reversed, but the entries streamed will be the same.   gt(大於),gte(大於或等於)定義了流範圍的下界。只有key大於(或等於)這個option的條目會被包含進這個範圍。當reverse=true,這個順序將會被反轉,但是條目流是相同的

  • lt (less than), lte (less than or equal) define the higher bound of the range to be streamed. Only entries where the key is less than (or equal to) this option will be included in the range. When reverse=true the order will be reversed, but the entries streamed will be the same.   lt(小於),lte(小於或等於)定義了流範圍的上界。只有key小於(或等於)這個option的條目會被包含進這個範圍。當reverse=true,這個順序將會被反轉,但是條目流是相同的

  • reverse (boolean, default: false): stream entries in reverse order. Beware that due to the way that stores like LevelDB work, a reverse seek can be slower than a forward seek. 以相反順序輸入流條目。注意,因為像LevelDB這樣的儲存器的工作方式,反向查詢將慢於正向查詢

  • limit (number, default: -1): limit the number of entries collected by this stream. This number represents a maximum number of entries and may not be reached if you get to the end of the range first. A value of -1 means there is no limit. When reverse=true the entries with the highest keys will be returned instead of the lowest keys.  限制被流選擇的條目的數量。這個數量代表了條目的最大數量,如果先到了範圍的結尾處,它可能不會被觸發。-1值意味著這裡沒有限制。當設定reverse=true條目將會從最高值的keys的方向被返回,而不是最低的keys方向。

  • keys (boolean, default: true): whether the results should contain keys. If set to true and values set to false then results will simply be keys, rather than objects with a key property. Used internally by the createKeyStream()method.  是否結果應該包含keys。如果設定為true,且values設定為false,結果將只有keys,而不是帶有key屬性的物件。通過createKeyStream()方法內部使用

  • values (boolean, default: true): whether the results should contain values. If set to true and keys set to falsethen results will simply be values, rather than objects with a value property. Used internally by the createValueStream() method. 是否結果應該包含values。如果設定為true,且keys設定為false,結果將只有values,而不是帶有value屬性的物件。通過createKeyStream()方法內部使用

Legacy options:遺留options

  • start: instead use gte 可用於替換gte

  • end: instead use lte 可用於替換lte

 

 

db.createKeyStream([options])

Returns a Readable Stream of keys rather than key-value pairs. Use the same options as described for createReadStream to control the range and direction.

返回一個keys的可讀流,而不是鍵值對。使用和在createReadStream中描述的相同的options去控制範圍了方向

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.

你也可以通過傳遞一個keys設定為true,values設定為false的options物件給createReadStream()來獲得該流。這兩個的結果是相等的;他們的流都在物件模組中被操作

db.createKeyStream()
  .on('data', function (data) {
    console.log('key=', data)
  })

// same as:
db.createReadStream({ keys: true, values: false })
  .on('data', function (data) {
    console.log('key=', data)
  })

 

 

 

db.createValueStream([options])

Returns a Readable Stream of values rather than key-value pairs. Use the same options as described for createReadStream to control the range and direction.

返回一個values的可讀流,而不是鍵值對。使用和在createReadStream中描述的相同的options去控制範圍了方向

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.

你也可以通過傳遞一個keys設定為false,values設定為true的options物件給createReadStream()來獲得該流。這兩個的結果是相等的;他們的流都在物件模組中被操作

db.createValueStream()
  .on('data', function (data) {
    console.log('value=', data)
  })

// same as:
db.createReadStream({ keys: false, values: true })
  .on('data', function (data) {
    console.log('value=', data)
  })

 

 

 

db.iterator([options])

Returns an abstract-leveldown iterator, 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.

返回一個抽象leveldown迭代器,用於加強上面的可讀流。其options與createReadStream()的範圍options是相同的,並且被傳遞給底層的儲存器

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, removing it was the best course of action.

為了提供一個更小且可儲存的程式碼,db.createWriteStream() 就被移除了。它主要存在是為了與db.createReadStream()方法對稱,但是通過更多的討論後,移除它會更好。

The main driver for this was performance. While db.createReadStream() performs well under most use cases, db.createWriteStream() was highly dependent on the application keys and values. Thus we can't provide a standard implementation and encourage more write-stream implementations to be created to solve the broad spectrum of use cases.

移除它的主要驅動是其效能。在大多數情況下,db.createReadStream()執行得很好,db.createWriteStream()則更多依賴於應用的keysvalues。因此,我們不能提供一個標準的實現,並鼓勵建立更多的寫流實現來解決廣泛的用例範圍

Check out the implementations that the community has already produced here.

請檢視社群已經在here生成的實現。