javascript - How do I write a Node.js module to handle an incoming piped stream -
i'm trying write node module accepts incoming piped binary (or base-64-encoded) stream, frankly don't know start. can't see examples in node docs handling incoming streams; see examples on consuming them?
say example want able this:
var asset = new projectasset('myfile', __dirname + '/image.jpg') var stream = fs.createreadstream(__dirname + '/image.jpg', { encoding: 'base64' }).pipe(asset) stream.on('finish', function() { done() })
i've gotten projectasset
looking this, i'm @ loss of go next:
'use strict' var stream = require('stream'), util = require('util') var projectasset = function() { var self = object.defineproperty(self, 'binarydata', { configurable: true, writable: true }) stream.stream.call(self) self.on('pipe', function(src) { // happen here? how set self.binarydata? }) return self } util.inherits(projectasset, stream.stream) module.exports = projectasset module.exports.default_file_name = 'file'
it possible inherit stream.stream
, make work, based on what's available in documentation suggest inheriting stream.writable
. piping stream.writable
you'll need have _write(chunk, encoding, done)
defined handle piping. here example:
var asset = new projectasset('myfile', __dirname + '/image.jpg') var stream = fs.createreadstream(__dirname + '/image.jpg', { encoding: 'base64' }).pipe(asset) stream.on('finish', function() { console.log(asset.binarydata); })
project asset
'use strict' var stream = require('stream'), util = require('util') var projectasset = function() { var self = self.data self.binarydata = []; stream.writable.call(self) self._write = function(chunk, encoding, done) { // can handle data want self.binarydata.push(chunk.tostring()) // call after processing data done() } self.on('finish', function() { self.data = buffer.concat(self.binarydata) }) return self } util.inherits(projectasset, stream.writable) module.exports = projectasset module.exports.default_file_name = 'file'
if you're looking read stream
, take @ inheriting stream.duplex
, including _read(size)
method.
there's simplified constructors api if you're doing simpler.
Comments
Post a Comment