Quick multipart post for nodejs
Mostly because I wanted to experiment, but also because I add hard time finding one that just work. My “reinvent the wheel” contribution to post a form/multipart via nodejs:
events = require 'events'
class Multipart extends events.EventEmitter
constructor: ()->
@boundary_length = 40
@random_boundary_part_length = 12
@boundary = @get_boundary()
@crlf = '\r\n'
get_boundary: ()->
# algorithm borrowed from curl Curl_FormBoundary
allowed_characters = "0123456789abcdef"
boundary = ''
for i in [1..@boundary_length-@random_boundary_part_length]
do (i)->
boundary += '-'
for i in [1..@random_boundary_part_length]
do (i)->
boundary += allowed_characters[Math.floor(Math.random() * 16)]
boundary
write: (string)->
@emit 'data', string
add_parameter: (name, value)->
@write "--#{@boundary}"
@write @crlf
@write "Content-Disposition: form-data; name=\"#{name}\""
@write @crlf
@write @crlf
@write value
@write @crlf
end: ()->
@write "--#{@boundary}"
@write "--"
@emit 'end'
module.exports = Multipart
Intended to be use like that:
https = require 'https'
Multipart = require './multipart'
m = new Multipart()
query = ''
m.on 'data', (data)->
query += data
m.on 'end', ()->
console.log 'sending request'
console.log query
req = https.request {port: 443, host: 'graph.facebook.com', method: 'POST', path: '/', headers: {'Content-Length': query.length, 'Content-Type': "multipart/form-data; boundary=#{m.boundary}"}}, (res)->
res.setEncoding('utf8')
console.log res.statusCode
console.log res.headers
res.on 'data', (chunk)->
console.log('BODY: ' + chunk)
req.write query
req.end()
m.add_parameter 'access_token', 'bla'
m.add_parameter 'batch', '[{"method":"GET","relative_url":"/me"},{"method":"GET","relative_url":"/me"}]'
m.end()
