Browse files

added support for callbacks

  • Loading branch information...
1 parent 136baaa commit e839e2d0bc41e05df950e74c48716010684205cb @pdfcrowd committed Apr 27, 2011
Showing with 40 additions and 32 deletions.
  1. +40 −32 lib/pdfcrowd.js
View
72 lib/pdfcrowd.js
@@ -1,32 +1,36 @@
var http = require('http');
var querystring = require('querystring');
+
var Pdfcrowd = function(username, apikey) {
this.username = username;
this.apikey = apikey;
-
this.httpOptions = {
host: 'pdfcrowd.com',
port: 80,
- // path: '/api/pdf/convert/html/',
method: 'POST',
- // headers: { 'content-length': postData.length,
- // 'content-type': 'application/x-www-form-urlencoded' }
+ };
+ this.callbacks = {
+ error: function() {
+ console.log("unhandled error");
+ },
+ pdf: function(rstream) {
+ rstream.close();
+ console.log("unhandled success");
+ }
};
};
-var clone_object = function(obj) {
- var prop, cloned = {};
- for (prop in obj) {
- if (typeof obj !== 'function') {
- cloned[prop] = obj[prop];
- }
- }
- return cloned;
+
+
+Pdfcrowd.prototype.on = function(event, callback) {
+ this.callbacks[event] = callback;
};
+
Pdfcrowd.prototype.convertHtml = function(server_res, html, options) {
+ var that = this;
// form POST data
var postData = clone_object(options);
@@ -42,39 +46,43 @@ Pdfcrowd.prototype.convertHtml = function(server_res, html, options) {
httpOptions['headers'] = { 'content-length': postData.length,
'content-type': 'application/x-www-form-urlencoded' };
-
var req = http.request(httpOptions, function(res) {
- console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
- res.on('end', function () {
- server_res.end();
- });
-
if (res.statusCode < 299) {
- server_res.setHeader("Content-Type", "application/pdf");
- server_res.setHeader("cache-control", "no-cache");
- server_res.setHeader("accept-ranges", "none");
- server_res.setHeader("content-disposition", "attachment; filename=\"generated.pdf\"");
- res.on('data', function (chunk) {
- server_res.write(chunk);
- });
+ that.callbacks['pdf'](res);
}
else {
- server_res.write("some error");
- server_res.end();
+ var err = [];
+ res.on('data', function(chunk) {
+ err.push(chunk.toString());
+ });
+ res.on('end', function() {
+ that.callbacks['error'](res.statusCode, err.join(''));
+ });
}
-
});
req.on('error', function(res) {
- console.log('STATUS: ' + res.statusCode);
- console.log('** ' + res);
- server_res.end('FATALek!\n');
+ that.callbacks['error'](res.statusCode, res.toString());
});
req.write(postData);
req.end();
}
-module.exports = Pdfcrowd;
+module.exports = Pdfcrowd;
+
+
+// ---------------------------------------------------------------------------
+// private
+
+var clone_object = function(obj) {
+ var prop, cloned = {};
+ for (prop in obj) {
+ if (typeof obj !== 'function') {
+ cloned[prop] = obj[prop];
+ }
+ }
+ return cloned;
+};

0 comments on commit e839e2d

Please sign in to comment.