Created
March 29, 2014 07:37
-
-
Save gildean/9850206 to your computer and use it in GitHub Desktop.
levelup vs. level-sublevel binary stream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var server = require('http').createServer(handler).listen(function () { console.log(this.address()); }); | |
var fs = require('fs'); | |
var levelup = require('level'); | |
var subLevel = require('level-sublevel'); | |
var dbPath = './test'; | |
if (!fs.existsSync(dbPath)) { | |
fs.mkdirSync(dbPath); | |
} | |
var db = subLevel(levelup(dbPath)); | |
var levelNames = ['wow', 'such', 'content']; | |
var subLevels = levelNames.reduce(function (obj, name) { | |
obj[name] = db.sublevel(name, { valueEncoding: 'json' }); | |
obj[name].ws = obj[name].createWriteStream({ type: 'put', valueEncoding: 'json' }); | |
obj[name].ws.write({ key: Date.now(), value: { foo: 'bar', bar: 'baz' } }); | |
return obj; | |
}, {}); | |
db.put(Date.now(), { foo: 'bar', bar: 'baz' }, { valueEncoding: 'json' }); | |
// get /levelup to read from the top level, otherwise a random sublevel is selected | |
function handler(req, res) { | |
if (req.url === '/' || req.url === '/levelup') { | |
res.writeHead(200, { 'Content-Type': 'application/json' }); | |
var options = { keys: false, values: true, valueEncoding: 'binary' }; | |
var rso = (req.url === '/levelup') ? db : subLevels[levelNames[Math.floor(Math.random() * 3)]]; | |
var rs = rso.createReadStream(options); | |
rs.on('data', function (data) { console.log('value from database:', typeof data, data); }); | |
return rs.pipe(res); | |
} | |
res.statusCode = 418; | |
res.end('all out of coffee...'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment