Introduction to LevelDB
Get and Put
var db = level('db1')
db.put('hello', 'world', function (err) {
db.get('hello', function (err, value) {
alert(value)
db.close()
})
})
Update
var db = level('db1')
db.get('hello', function (err, value) {
alert(value)
db.put('hello', 'matteo', function (err) {
db.get('hello', function (err, value) {
alert(value)
db.close()
})
})
})
Streams
var db = level('db1')
var stream = db.createReadStream()
stream.on('data', function (chunk) {
alert(JSON.stringify(chunk))
})
stream.on('end', function () {
alert('ended')
db.close()
})
Batch!
var db = level('db1')
db.batch([{
key: 'hello1', value: 'abcde'
}, {
key: 'the answer', value: '42'
}], function (err) {
alert('all inserted!')
db.close()
})
Streams
var db = level('db1')
var stream = db.createReadStream()
stream.on('data', function (chunk) {
alert(JSON.stringify(chunk))
})
stream.on('end', function () {
db.close()
})
Stream, reverse order
var db = level('db1')
var stream = db.createReadStream({ reverse: true })
stream.on('data', function (chunk) {
alert(JSON.stringify(chunk))
})
stream.on('end', function () {
db.close()
})
Store an Object
var db = level('obj-store')
var batch = [
{ date: '1994-11-05', body: 'my body' },
{ date: '2003-07-22', body: 'my body2' },
{ date: '2015-07-23', body: 'my body3' }
].reduce(function (acc, article) {
article.id = uuid.v4()
var key = 'art:' + article.id
acc.push({ key: key, value: JSON.stringify(article), type: 'put' })
acc.push({ key: 'date:' + article.date + ':' + article.id,
value: key, type: 'put' })
return acc
}, [])
db.batch(batch, function (err) { alert('all inserted'); db.close() })
Lookup
var db = level('obj-store')
db.createReadStream({ gte: 'date:2003', lt: 'date:2017' })
.pipe(through.obj(function (obj, enc, cb) {
db.get(obj.value, cb)
}))
.on('data', function (data) {
alert(JSON.stringify(data))
})
.on('end', db.close.bind(db))