Last active
August 22, 2018 22:29
-
-
Save dbalduini/50c0c095c478dcb82323b02104f2d852 to your computer and use it in GitHub Desktop.
post base64 binary data with nodejs request module
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
const convert = require('buffer-to-stream'); | |
const request = require('request'); | |
/** | |
* Post binary data in base64. | |
* @param opt The request options | |
* @param data The binary data in base64 string | |
* @param cb The request callback | |
*/ | |
function _postBinaryData(opt, data, cb) { | |
const buf = Buffer.from(data, 'base64'); | |
const readable = convert(buf); | |
opt.headers = opt.headers || {}; | |
opt.headers['Content-Length'] = Buffer.byteLength(buf); | |
let chunk = ''; | |
let res = null; | |
let err = null; | |
let stream = request | |
.post(opt) | |
.on('response', function (response) { | |
res = response; | |
}) | |
.on('data', function (buffer) { | |
chunk += buffer.toString(); | |
}) | |
.on('end', function () { | |
cb(err, res, chunk); | |
}) | |
.on('error', function (error) { | |
err = error; | |
}); | |
readable.pipe(stream); | |
} | |
// Promisify postBinaryData | |
function postBinaryData(opt, data) { | |
return new Promise((resolve, reject) => { | |
_postBinaryData(opt, data, (err, res, body) => { | |
if (err) { | |
reject(err); | |
} else { | |
resolve(body); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample Usage