javascript - Accessing the Node ReadStream -


i have piece of code wrapped in promise. piece of code reads image form http, various things, , @ end sends aws.s3.putobject. looks (simplified): please note form multiparty object.

form.on('part', (part) => {//form multiparty     filecount++;     let tmpfile = path.join(os.tmpdir(), `${userid}_${timeprefix}_${path.basename(part.filename)}`);     part.pipe(fs.createwritestream(tmpfile));     part.on('end', () => {         resolve(fs.createreadstream(tmpfile));     });     part.once('error', (error) => {         handleerror(error);     }); });  form.once('error', (error) => {     handleerror(error); });  form.parse(request); }).then((imagestream) => {    //here call aws s3.putobject. return promise }).then(() => {     return new ok(); }); 

in essence stream made on created image , sent aws. wanted manipulation on binary level (read file signature, check if image). got work this:

form.on('part', (part) => {     filecount++;      let tmpfile = path.join(os.tmpdir(), `${userid}_${timeprefix}_${path.basename(part.filename)}`);     part.pipe(fs.createwritestream(tmpfile));     part.on('end', () => {         let chunk = [];         let file = fs.createreadstream(tmpfile);         let isfirstchunkset = false;         file.on('data', function(chunks) {             if (!isfirstchunkset){                 chunk = chunks;                 isfirstchunkset = true;             }         });          file.on('close', function() {             let magicnumber = chunk.tostring('hex', 0, 2);                         if (imageproperties.allowed_file_types.includes(magicnumber)) {                 resolve(fs.createreadstream(tmpfile));             } else {                 error.message = 'wrong file type';                 handleerror(error);             }         });     });     part.once('error', (error) => {         handleerror(error);     }); });  form.once('error', (error) => {     handleerror(error); });  form.parse(request); }).then((imagestream) => {     //here call aws s3.putobject. return promise }).then(() => {     return new ok(); }); 

basically attached 2 event listeners existing stream access data, , checking on header file.

what bothers me feeling overdoing things here. avoid 2 listeners (data , close) , read stream if possible.

to more precise, section of code receives stream, , inside access data before sending aws. stream ready, , put how read it, without using events?

form.parse(request); }).then((imagestream) => {     //how can access imagestream here, without event listeners.     //assumption stream ready accessed.      //here call aws s3.putobject. return promise }).then(() => {     return new ok(); }); 


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -