Last active
December 6, 2018 02:18
-
-
Save IronSavior/64c0447c44070084dca6529b1a33ae3c to your computer and use it in GitHub Desktop.
S3.listObjectsV2 as stream
This file contains hidden or 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
"use strict"; | |
const {Readable} = require('readable-stream'); | |
const {S3} = require('aws-sdk'); | |
// Convert the given S3::listObjectsV2 request to a Readable stream | |
// req should be an un-sent S3::listObjectsV2() request | |
// opts are typical stream options. Object mode is required. | |
function s3_list_stream( req, opts ){ | |
opts = Object.assign({}, opts, {read, objectMode: true}); | |
const stream = new Readable(opts); | |
return stream; | |
function read(){ | |
if( !req ) return; | |
const _req = req; | |
req = null; | |
_req.send(page_handler); | |
} | |
function page_handler( e, data ){ | |
if( e ) return stream.destroy(e); | |
for( let obj of data.Contents ){ | |
obj.Bucket = data.Name; | |
stream.push(obj); | |
} | |
req = this.hasNextPage() ? this.nextPage() : null; | |
if( !req ) stream.push(null); | |
} | |
} | |
function test_count_objects(){ | |
const list_req = new S3().listObjectsV2({ | |
Bucket: 'NEED', | |
Prefix: 'MAYBE NEED' | |
}); | |
const list_stream = s3_list_stream(list_req); | |
let count = 0; | |
list_stream.on('data', _ => count++); | |
return new Promise(done => list_stream.once('end', _ => done(count))); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment