Skip to content

Instantly share code, notes, and snippets.

@fergiemcdowall
Last active January 10, 2022 14:56
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fergiemcdowall/5375331 to your computer and use it in GitHub Desktop.
Save fergiemcdowall/5375331 to your computer and use it in GitHub Desktop.
A Gist to demonstrate writing and reading image files to LevelDB via the node module level up
var levelup = require('levelup')
var fs = require('fs');
var db = levelup('./imagedb')
db.put('name', fs.readFileSync('image.png'), { encoding: 'binary' }, function (err) {
db.get('name', { encoding: 'binary' }, function (err, value) {
fs.writeFile('image-copy.png', value, function (err) {
console.log('image-copy.png saved!');
});
})
})
{
"name": "LevelDBFileReader",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node LevelDBFileReader.js"
},
"dependencies": {
"levelup": "*"
}
}
@juliangruber
Copy link

here's how to do it in a streaming way:

var level = require('level');
var Store = require('level-store');
var db = level(__dirname + '/db', { valueEncoding: 'binary' });
var store = Store(db);

fs.createReadStream('image.png')
  .pipe(store.createWriteStream('image'));
store.createReadStream('image', { live: true })
  .pipe(fs.createWriteStream('image-copy.png'))
  .on('close', function () {
    console.log('image-copy.png saved!');
  });

@olegakbarov
Copy link

i somehow got a this.db.createWriteStream is not a function when try to make a stream, i might be missing something obvious :(

here's my relevant code

const db = levelup(`${__dirname}/db`, { valueEncoding: 'binary' });
const store = Store(db);
const upload = multer({ dest: './uploads/' });

app.post('/', upload.single('image'), (req, res, next) => {
  store.createWriteStream(`${__dirname}/${req.file.path}`)
  ...
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment