var uuid = require('node-uuid')
, CombinedStream = require('combined-stream')
, isstream = require('isstream')
function Multipart (request) {
Multipart.prototype.isChunked = function (options) {
, parts = options.data || options
self.request.emit('error', new Error('Argument error, options.multipart.'))
if (options.chunked !== undefined) {
chunked = options.chunked
if (self.request.getHeader('transfer-encoding') === 'chunked') {
parts.forEach(function (part) {
if (typeof part.body === 'undefined') {
self.request.emit('error', new Error('Body attribute missing in multipart.'))
if (isstream(part.body)) {
Multipart.prototype.setHeaders = function (chunked) {
if (chunked && !self.request.hasHeader('transfer-encoding')) {
self.request.setHeader('transfer-encoding', 'chunked')
var header = self.request.getHeader('content-type')
if (!header || header.indexOf('multipart') === -1) {
self.request.setHeader('content-type', 'multipart/related; boundary=' + self.boundary)
if (header.indexOf('boundary') !== -1) {
self.boundary = header.replace(/.*boundary=([^\s;]+).*/, '$1')
self.request.setHeader('content-type', header + '; boundary=' + self.boundary)
Multipart.prototype.build = function (parts, chunked) {
var body = chunked ? new CombinedStream() : []
return chunked ? body.append(part) : body.push(new Buffer(part))
if (self.request.preambleCRLF) {
parts.forEach(function (part) {
var preamble = '--' + self.boundary + '\r\n'
Object.keys(part).forEach(function (key) {
if (key === 'body') { return }
preamble += key + ': ' + part[key] + '\r\n'
add('--' + self.boundary + '--')
if (self.request.postambleCRLF) {
Multipart.prototype.onRequest = function (options) {
var chunked = self.isChunked(options)
, parts = options.data || options
self.body = self.build(parts, chunked)
exports.Multipart = Multipart