Skip to content

Instantly share code, notes, and snippets.

@dbalduini
Last active August 22, 2018 22:29
Show Gist options
  • Save dbalduini/50c0c095c478dcb82323b02104f2d852 to your computer and use it in GitHub Desktop.
Save dbalduini/50c0c095c478dcb82323b02104f2d852 to your computer and use it in GitHub Desktop.
post base64 binary data with nodejs request module
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);
}
});
}
}
@dbalduini
Copy link
Author

Sample Usage

const contentUrl = 'data:application/pdf;base64,JVBERi0xLjQNC..';

const data = contentUrl.split(';base64,').pop();

const opt = {
  uri: 'https://example.com/v1/media',
  headers: {
       'Content-Type': 'application/pdf'
    }
};

postBinaryData(opt, data).then(body => {
    console.log(JSON.parse(body));
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment