Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Merge pull request #1 from holman/npm

deployed happily on heroku
  • Loading branch information...
commit 95faca78043839522d1f4bdd0cc972f60d967866 2 parents 39fbe0a + 5e92989
@atmos atmos authored
View
1  .gitignore
@@ -0,0 +1 @@
+node_modules
View
399 imagemagick.js
@@ -1,399 +0,0 @@
-// lovingly created by @rsms:
-// https://github.com/rsms/node-imagemagick
-
-var sys = require('sys'),
- childproc = require('child_process'),
- EventEmitter = require('events').EventEmitter;
-
-
-function exec2(file, args /*, options, callback */) {
- var options = { encoding: 'utf8'
- , timeout: 0
- , maxBuffer: 500*1024
- , killSignal: 'SIGKILL'
- , output: null
- };
-
- var callback = arguments[arguments.length-1];
- if ('function' != typeof callback) callback = null;
-
- if (typeof arguments[2] == 'object') {
- var keys = Object.keys(options);
- for (var i = 0; i < keys.length; i++) {
- var k = keys[i];
- if (arguments[2][k] !== undefined) options[k] = arguments[2][k];
- }
- }
-
- var child = childproc.spawn(file, args);
- var killed = false;
- var timedOut = false;
-
- var Wrapper = function(proc) {
- this.proc = proc;
- this.stderr = new Accumulator();
- proc.emitter = new EventEmitter();
- proc.on = proc.emitter.on.bind(proc.emitter);
- this.out = proc.emitter.emit.bind(proc.emitter, 'data');
- this.err = this.stderr.out.bind(this.stderr);
- this.errCurrent = this.stderr.current.bind(this.stderr);
- };
- Wrapper.prototype.finish = function(err) {
- this.proc.emitter.emit('end', err, this.errCurrent());
- };
-
- var Accumulator = function(cb) {
- this.stdout = {contents: ""};
- this.stderr = {contents: ""};
- this.callback = cb;
-
- var limitedWrite = function(stream) {
- return function(chunk) {
- stream.contents += chunk;
- if (!killed && stream.contents.length > options.maxBuffer) {
- child.kill(options.killSignal);
- killed = true;
- }
- };
- };
- this.out = limitedWrite(this.stdout);
- this.err = limitedWrite(this.stderr);
- };
- Accumulator.prototype.current = function() { return this.stdout.contents; };
- Accumulator.prototype.errCurrent = function() { return this.stderr.contents; };
- Accumulator.prototype.finish = function(err) { this.callback(err, this.stdout.contents, this.stderr.contents); };
-
- var std = callback ? new Accumulator(callback) : new Wrapper(child);
-
- var timeoutId;
- if (options.timeout > 0) {
- timeoutId = setTimeout(function () {
- if (!killed) {
- child.kill(options.killSignal);
- timedOut = true;
- killed = true;
- timeoutId = null;
- }
- }, options.timeout);
- }
-
- child.stdout.setEncoding(options.encoding);
- child.stderr.setEncoding(options.encoding);
-
- child.stdout.addListener("data", function (chunk) { std.out(chunk, options.encoding); });
- child.stderr.addListener("data", function (chunk) { std.err(chunk, options.encoding); });
-
- child.addListener("exit", function (code, signal) {
- if (timeoutId) clearTimeout(timeoutId);
- if (code === 0 && signal === null) {
- std.finish(null);
- } else {
- var e = new Error("Command "+(timedOut ? "timed out" : "failed")+": " + std.errCurrent());
- e.timedOut = timedOut;
- e.killed = killed;
- e.code = code;
- e.signal = signal;
- std.finish(e);
- }
- });
-
- return child;
-};
-
-
-function parseIdentify(input) {
- var lines = input.split("\n"),
- prop = {},
- props = [prop],
- prevIndent = 0,
- indents = [indent],
- currentLine, comps, indent;
-
- lines.shift(); //drop first line (Image: name.jpg)
-
- for (i in lines) {
- currentLine = lines[i];
- if (currentLine.length > 0) {
- indent = currentLine.search(/\S/);
- comps = currentLine.split(': ');
- if (indent > prevIndent) indents.push(indent);
- while (indent < prevIndent) {
- indents.pop();
- prop = props.pop();
- prevIndent = indents[indents.length - 1];
- }
- if (comps.length < 2) {
- props.push(prop);
- prop = prop[currentLine.split(':')[0].trim().toLowerCase()] = {};
- } else {
- prop[comps[0].trim().toLowerCase()] = comps[1].trim()
- }
- prevIndent = indent;
- }
- }
- return props[0];
-};
-
-exports.identify = function(pathOrArgs, callback) {
- var isCustom = Array.isArray(pathOrArgs),
- isData,
- args = isCustom ? ([]).concat(pathOrArgs) : ['-verbose', pathOrArgs];
-
- if (typeof args[args.length-1] === 'object') {
- isData = true;
- pathOrArgs = args[args.length-1];
- args[args.length-1] = '-';
- if (!pathOrArgs.data)
- throw new Error('first argument is missing the "data" member');
- } else if (typeof pathOrArgs === 'function') {
- args[args.length-1] = '-';
- callback = pathOrArgs;
- }
- var proc = exec2(exports.identify.path, args, {timeout:120000}, function(err, stdout, stderr) {
- var result, geometry;
- if (!err) {
- if (isCustom) {
- result = stdout;
- } else {
- result = parseIdentify(stdout);
- geometry = result['geometry'].split(/x/);
-
- result.format = result.format.match(/\S*/)[0]
- result.width = parseInt(geometry[0]);
- result.height = parseInt(geometry[1]);
- result.depth = parseInt(result.depth);
- if (result.quality !== undefined) result.quality = parseInt(result.quality) / 100;
- }
- }
- callback(err, result);
- });
- if (isData) {
- if ('string' === typeof pathOrArgs.data) {
- proc.stdin.setEncoding('binary');
- proc.stdin.write(pathOrArgs.data, 'binary');
- proc.stdin.end();
- } else {
- proc.stdin.end(pathOrArgs.data);
- }
- }
- return proc;
-}
-exports.identify.path = 'identify';
-
-function ExifDate(value) {
- // YYYY:MM:DD HH:MM:SS -> Date(YYYY-MM-DD HH:MM:SS +0000)
- value = value.split(/ /);
- return new Date(value[0].replace(/:/g, '-')+' '+
- value[1]+' +0000');
-}
-
-function exifKeyName(k) {
- return k.replace(exifKeyName.RE, function(x){
- if (x.length === 1) return x.toLowerCase();
- else return x.substr(0,x.length-1).toLowerCase()+x.substr(x.length-1);
- });
-}
-exifKeyName.RE = /^[A-Z]+/;
-
-var exifFieldConverters = {
- // Numbers
- bitsPerSample:Number, compression:Number, exifImageLength:Number,
- exifImageWidth:Number, exifOffset:Number, exposureProgram:Number,
- flash:Number, imageLength:Number, imageWidth:Number, isoSpeedRatings:Number,
- jpegInterchangeFormat:Number, jpegInterchangeFormatLength:Number,
- lightSource:Number, meteringMode:Number, orientation:Number,
- photometricInterpretation:Number, planarConfiguration:Number,
- resolutionUnit:Number, rowsPerStrip:Number, samplesPerPixel:Number,
- sensingMethod:Number, stripByteCounts:Number, subSecTime:Number,
- subSecTimeDigitized:Number, subSecTimeOriginal:Number, customRendered:Number,
- exposureMode:Number, focalLengthIn35mmFilm:Number, gainControl:Number,
- saturation:Number, sharpness:Number, subjectDistanceRange:Number,
- subSecTime:Number, subSecTimeDigitized:Number, subSecTimeOriginal:Number,
- whiteBalance:Number, sceneCaptureType:Number,
-
- // Dates
- dateTime:ExifDate, dateTimeDigitized:ExifDate, dateTimeOriginal:ExifDate
-};
-
-exports.readMetadata = function(path, callback) {
- return exports.identify(['-format', '%[EXIF:*]', path], function(err, stdout) {
- var meta = {};
- if (!err) {
- stdout.split(/\n/).forEach(function(line){
- var eq_p = line.indexOf('=');
- if (eq_p === -1) return;
- var key = line.substr(0, eq_p).replace('/','-'),
- value = line.substr(eq_p+1).trim(),
- typekey = 'default';
- var p = key.indexOf(':');
- if (p !== -1) {
- typekey = key.substr(0, p);
- key = key.substr(p+1);
- if (typekey === 'exif') {
- key = exifKeyName(key);
- var converter = exifFieldConverters[key];
- if (converter) value = converter(value);
- }
- }
- if (!(typekey in meta)) meta[typekey] = {key:value};
- else meta[typekey][key] = value;
- })
- }
- callback(err, meta);
- });
-}
-
-exports.convert = function(args, timeout, callback) {
- var procopt = {encoding: 'binary'};
- if (typeof timeout === 'function') {
- callback = timeout;
- timeout = 0;
- } else if (typeof timeout !== 'number') {
- timeout = 0;
- }
- if (timeout && (timeout = parseInt(timeout)) > 0 && !isNaN(timeout))
- procopt.timeout = timeout;
- return exec2(exports.convert.path, args, procopt, callback);
-}
-exports.convert.path = 'convert';
-
-var resizeCall = function(t, callback) {
- var proc = exports.convert(t.args, t.opt.timeout, callback);
- if (t.opt.srcPath.match(/-$/)) {
- if ('string' === typeof t.opt.srcData) {
- proc.stdin.setEncoding('binary');
- proc.stdin.write(t.opt.srcData, 'binary');
- proc.stdin.end();
- } else {
- proc.stdin.end(t.opt.srcData);
- }
- }
- return proc;
-}
-
-exports.resize = function(options, callback) {
- var t = exports.resizeArgs(options);
- return resizeCall(t, callback)
-}
-
-exports.crop = function (options, callback) {
- if (typeof options !== 'object')
- throw new TypeError('First argument must be an object');
- if (!options.srcPath)
- throw new TypeError("No srcPath defined");
- if (!options.dstPath)
- throw new TypeError("No dstPath defined");
- if (!options.height && !options.width)
- throw new TypeError("No width or height defined");
-
- exports.identify(options.srcPath, function(err, meta) {
- if (err) return callback && callback(err);
- var t = exports.resizeArgs(options),
- ignoreArg = false,
- args = [];
- t.args.forEach(function (arg) {
- // ignoreArg is set when resize flag was found
- if (!ignoreArg && (arg != '-resize'))
- args.push(arg);
- // found resize flag! ignore the next argument
- if (arg == '-resize')
- ignoreArg = true;
- // found the argument after the resize flag; ignore it and set crop options
- if ((arg != "-resize") && ignoreArg) {
- var dSrc = meta.width / meta.height,
- dDst = t.opt.width / t.opt.height,
- resizeTo = (dSrc < dDst) ? ''+t.opt.width+'x' : 'x'+t.opt.height;
- args = args.concat([
- '-resize', resizeTo,
- '-gravity', 'Center',
- '-crop', ''+t.opt.width + 'x' + t.opt.height + '+0+0',
- '+repage'
- ]);
- ignoreArg = false;
- }
- })
-
- t.args = args;
- resizeCall(t, callback);
- })
-}
-
-exports.resizeArgs = function(options) {
- var opt = {
- srcPath: null,
- srcData: null,
- srcFormat: null,
- dstPath: null,
- quality: 0.8,
- format: 'jpg',
- progressive: false,
- colorspace: null,
- width: 0,
- height: 0,
- strip: true,
- filter: 'Lagrange',
- sharpening: 0.2,
- customArgs: [],
- timeout: 0
- }
-
- // check options
- if (typeof options !== 'object')
- throw new Error('first argument must be an object');
- for (var k in opt) if (k in options) opt[k] = options[k];
- if (!opt.srcPath && !opt.srcData)
- throw new Error('both srcPath and srcData are empty');
-
- // normalize options
- if (!opt.format) opt.format = 'jpg';
- if (!opt.srcPath) {
- opt.srcPath = (opt.srcFormat ? opt.srcFormat +':-' : '-');
- }
- if (!opt.dstPath)
- opt.dstPath = (opt.format ? opt.format+':-' : '-'); // stdout
- if (opt.width === 0 && opt.height === 0)
- throw new Error('both width and height can not be 0 (zero)');
-
- // build args
- var args = [opt.srcPath];
- if (opt.sharpening > 0) {
- args = args.concat([
- '-set', 'option:filter:blur', String(1.0-opt.sharpening)]);
- }
- if (opt.filter) {
- args.push('-filter');
- args.push(opt.filter);
- }
- if (opt.strip) {
- args.push('-strip');
- }
- if (opt.width || opt.height) {
- args.push('-resize');
- if (opt.height === 0) args.push(String(opt.width));
- else if (opt.width === 0) args.push('x'+String(opt.height));
- else args.push(String(opt.width)+'x'+String(opt.height));
- }
- opt.format = opt.format.toLowerCase();
- var isJPEG = (opt.format === 'jpg' || opt.format === 'jpeg');
- if (isJPEG && opt.progressive) {
- args.push('-interlace');
- args.push('plane');
- }
- if (isJPEG || opt.format === 'png') {
- args.push('-quality');
- args.push(Math.round(opt.quality * 100.0).toString());
- }
- else if (opt.format === 'miff' || opt.format === 'mif') {
- args.push('-quality');
- args.push(Math.round(opt.quality * 9.0).toString());
- }
- if (opt.colorspace) {
- args.push('-colorspace');
- args.push(opt.colorspace);
- }
- if (Array.isArray(opt.customArgs) && opt.customArgs.length)
- args = args.concat(opt.customArgs);
- args.push(opt.dstPath);
-
- return {opt:opt, args:args};
-}
View
7 index.js
@@ -2,10 +2,9 @@ http = require('http')
fs = require('fs')
url = require('url')
-require('./mimetypes')
-req = require('./request')
-server = require('./node-router').getServer()
-im = require('./imagemagick')
+req = require('request')
+server = require('node-router').getServer()
+im = require('imagemagick')
function fetch(query,cb){
var google = 'http://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=8&q=' + query
View
146 mimetypes.js
@@ -1,146 +0,0 @@
-// from http://github.com/felixge/node-paperboy
-exports.types = {
- "aiff":"audio/x-aiff",
- "arj":"application/x-arj-compressed",
- "asf":"video/x-ms-asf",
- "asx":"video/x-ms-asx",
- "au":"audio/ulaw",
- "avi":"video/x-msvideo",
- "bcpio":"application/x-bcpio",
- "ccad":"application/clariscad",
- "cod":"application/vnd.rim.cod",
- "com":"application/x-msdos-program",
- "cpio":"application/x-cpio",
- "cpt":"application/mac-compactpro",
- "csh":"application/x-csh",
- "css":"text/css",
- "deb":"application/x-debian-package",
- "dl":"video/dl",
- "doc":"application/msword",
- "drw":"application/drafting",
- "dvi":"application/x-dvi",
- "dwg":"application/acad",
- "dxf":"application/dxf",
- "dxr":"application/x-director",
- "etx":"text/x-setext",
- "ez":"application/andrew-inset",
- "fli":"video/x-fli",
- "flv":"video/x-flv",
- "gif":"image/gif",
- "gl":"video/gl",
- "gtar":"application/x-gtar",
- "gz":"application/x-gzip",
- "hdf":"application/x-hdf",
- "hqx":"application/mac-binhex40",
- "html":"text/html",
- "ice":"x-conference/x-cooltalk",
- "ico":"image/x-icon",
- "ief":"image/ief",
- "igs":"model/iges",
- "ips":"application/x-ipscript",
- "ipx":"application/x-ipix",
- "jad":"text/vnd.sun.j2me.app-descriptor",
- "jar":"application/java-archive",
- "jpeg":"image/jpeg",
- "jpg":"image/jpeg",
- "js":"text/javascript",
- "json":"application/json",
- "latex":"application/x-latex",
- "lsp":"application/x-lisp",
- "lzh":"application/octet-stream",
- "m":"text/plain",
- "m3u":"audio/x-mpegurl",
- "man":"application/x-troff-man",
- "me":"application/x-troff-me",
- "midi":"audio/midi",
- "mif":"application/x-mif",
- "mime":"www/mime",
- "movie":"video/x-sgi-movie",
- "mustache":"text/plain",
- "mp4":"video/mp4",
- "mpg":"video/mpeg",
- "mpga":"audio/mpeg",
- "ms":"application/x-troff-ms",
- "nc":"application/x-netcdf",
- "oda":"application/oda",
- "ogm":"application/ogg",
- "pbm":"image/x-portable-bitmap",
- "pdf":"application/pdf",
- "pgm":"image/x-portable-graymap",
- "pgn":"application/x-chess-pgn",
- "pgp":"application/pgp",
- "pm":"application/x-perl",
- "png":"image/png",
- "pnm":"image/x-portable-anymap",
- "ppm":"image/x-portable-pixmap",
- "ppz":"application/vnd.ms-powerpoint",
- "pre":"application/x-freelance",
- "prt":"application/pro_eng",
- "ps":"application/postscript",
- "qt":"video/quicktime",
- "ra":"audio/x-realaudio",
- "rar":"application/x-rar-compressed",
- "ras":"image/x-cmu-raster",
- "rgb":"image/x-rgb",
- "rm":"audio/x-pn-realaudio",
- "rpm":"audio/x-pn-realaudio-plugin",
- "rtf":"text/rtf",
- "rtx":"text/richtext",
- "scm":"application/x-lotusscreencam",
- "set":"application/set",
- "sgml":"text/sgml",
- "sh":"application/x-sh",
- "shar":"application/x-shar",
- "silo":"model/mesh",
- "sit":"application/x-stuffit",
- "skt":"application/x-koan",
- "smil":"application/smil",
- "snd":"audio/basic",
- "sol":"application/solids",
- "spl":"application/x-futuresplash",
- "src":"application/x-wais-source",
- "stl":"application/SLA",
- "stp":"application/STEP",
- "sv4cpio":"application/x-sv4cpio",
- "sv4crc":"application/x-sv4crc",
- "svg":"image/svg+xml",
- "swf":"application/x-shockwave-flash",
- "tar":"application/x-tar",
- "tcl":"application/x-tcl",
- "tex":"application/x-tex",
- "texinfo":"application/x-texinfo",
- "tgz":"application/x-tar-gz",
- "tiff":"image/tiff",
- "tr":"application/x-troff",
- "tsi":"audio/TSP-audio",
- "tsp":"application/dsptype",
- "tsv":"text/tab-separated-values",
- "unv":"application/i-deas",
- "ustar":"application/x-ustar",
- "vcd":"application/x-cdlink",
- "vda":"application/vda",
- "vivo":"video/vnd.vivo",
- "vrm":"x-world/x-vrml",
- "wav":"audio/x-wav",
- "wax":"audio/x-ms-wax",
- "wma":"audio/x-ms-wma",
- "wmv":"video/x-ms-wmv",
- "wmx":"video/x-ms-wmx",
- "wrl":"model/vrml",
- "wvx":"video/x-ms-wvx",
- "xbm":"image/x-xbitmap",
- "xlw":"application/vnd.ms-excel",
- "xml":"text/xml",
- "xpm":"image/x-xpixmap",
- "xwd":"image/x-xwindowdump",
- "xyz":"chemical/x-pdb",
- "zip":"application/zip",
-};
-
-exports.lookup = function(ext, defaultType) {
- defaultType = defaultType || 'application/octet-stream';
-
- return (ext in exports.types)
- ? exports.types[ext]
- : defaultType;
-};
View
558 node-router.js
@@ -1,558 +0,0 @@
-/*
-Copyright (c) 2010 Tim Caswell <tim@creationix.com>
-
-Permission is hereby granted, free of charge, to any person
-obtaining a copy of this software and associated documentation
-files (the "Software"), to deal in the Software without
-restriction, including without limitation the rights to use,
-copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the
-Software is furnished to do so, subject to the following
-conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-OTHER DEALINGS IN THE SOFTWARE.
-*/
-
-var sys = require('sys');
-var fs = require('fs');
-var path = require('path');
-var http = require('http');
-var url_parse = require("url").parse;
-
-// Used as a simple, convient 404 handler.
-function notFound(req, res, message) {
- message = (message || "Not Found\n") + "";
- res.writeHead(404, {
- "Content-Type": "text/plain",
- "Content-Length": message.length
- });
- if (req.method !== "HEAD")
- res.write(message);
- res.end();
-}
-
-// Modifies req and res to call logger with a log line on each res.end
-// Think of it as "middleware"
-function logify(req, res, logger) {
- var end = res.end;
- res.end = function () {
- // Common Log Format (mostly)
- logger((req.socket && req.socket.remoteAddress) + " - - [" + (new Date()).toUTCString() + "]"
- + " \"" + req.method + " " + req.url
- + " HTTP/" + req.httpVersionMajor + "." + req.httpVersionMinor + "\" "
- + res.statusCode + " - \""
- + (req.headers['referer'] || "") + "\" \"" + (req.headers["user-agent"] ? req.headers["user-agent"].split(' ')[0] : '') + "\"");
- return end.apply(this, arguments);
- }
- var writeHead = res.writeHead;
- res.writeHead = function (code) {
- res.statusCode = code;
- return writeHead.apply(this, arguments);
- }
-}
-
-exports.getServer = function getServer(logger) {
-
- logger = logger || sys.puts;
-
- var routes = [];
-
- // Adds a route the the current server
- function addRoute(method, pattern, handler, format) {
- if (typeof pattern === 'string') {
- pattern = new RegExp("^" + pattern + "$");
- }
- var route = {
- method: method,
- pattern: pattern,
- handler: handler
- };
- if (format !== undefined) {
- route.format = format;
- }
- routes.push(route);
- }
-
- // The four verbs are wrappers around addRoute
- function get(pattern, handler) {
- return addRoute("GET", pattern, handler);
- }
- function post(pattern, handler, format) {
- return addRoute("POST", pattern, handler, format);
- }
- function put(pattern, handler, format) {
- return addRoute("PUT", pattern, handler, format);
- }
- function del(pattern, handler) {
- return addRoute("DELETE", pattern, handler);
- }
- function head(pattern, handler) {
- return addRoute("HEAD", pattern, handler);
- }
-
- // This is a meta pattern that expands to a common RESTful mapping
- function resource(name, controller, format) {
- get(new RegExp('^/' + name + '$'), controller.index);
- get(new RegExp('^/' + name + '/([^/]+)$'), controller.show);
- post(new RegExp('^/' + name + '$'), controller.create, format);
- put(new RegExp('^/' + name + '/([^/]+)$'), controller.update, format);
- del(new RegExp('^/' + name + '/([^/]+)$'), controller.destroy);
- };
-
- function resourceController(name, data, on_change) {
- data = data || [];
- on_change = on_change || function () {};
- return {
- index: function (req, res) {
- res.simpleJson(200, {content: data, self: '/' + name});
- },
- show: function (req, res, id) {
- var item = data[id];
- if (item) {
- res.simpleJson(200, {content: item, self: '/' + name + '/' + id});
- } else {
- res.notFound();
- }
- },
- create: function (req, res) {
- req.jsonBody(function (json) {
- var item, id, url;
- item = json && json.content;
- if (!item) {
- res.notFound();
- } else {
- data.push(item);
- id = data.length - 1;
- on_change(id);
- url = "/" + name + "/" + id;
- res.simpleJson(201, {content: item, self: url}, [["Location", url]]);
- }
- });
- },
- update: function (req, res, id) {
- req.jsonBody(function (json) {
- var item = json && json.content;
- if (!item) {
- res.notFound();
- } else {
- data[id] = item;
- on_change(id);
- res.simpleJson(200, {content: item, self: "/" + name + "/" + id});
- }
- });
- },
- destroy: function (req, res, id) {
- delete data[id];
- on_change(id);
- res.simpleJson(200, "200 Destroyed");
- }
- };
- };
-
- // Create the http server object
- var server = http.createServer(function (req, res) {
-
- // Enable logging on all requests using common-logger style
- logify(req, res, logger);
-
- var uri, path;
-
- // Performs an HTTP 302 redirect
- res.redirect = function redirect(location) {
- res.writeHead(302, {"Location": location});
- res.end();
- }
-
- // Performs an internal redirect
- res.innerRedirect = function innerRedirect(location) {
- logger("Internal Redirect: " + req.url + " -> " + location);
- req.url = location;
- doRoute();
- }
-
- function simpleResponse(code, body, content_type, extra_headers) {
- res.writeHead(code, (extra_headers || []).concat(
- [ ["Content-Type", content_type],
- ["Content-Length", Buffer.byteLength(body, 'utf8')]
- ]));
- if (req.method !== "HEAD")
- res.write(body, 'utf8');
- res.end();
- }
-
- res.simpleText = function (code, body, extra_headers) {
- simpleResponse(code, body, "text/plain", extra_headers);
- };
-
- res.simpleHtml = function (code, body, extra_headers) {
- simpleResponse(code, body, "text/html", extra_headers);
- };
-
- res.simpleJson = function (code, json, extra_headers) {
- simpleResponse(code, JSON.stringify(json), "application/json", extra_headers);
- };
-
- res.notFound = function (message) {
- notFound(req, res, message);
- };
-
- res.onlyHead = function (code, extra_headers) {
- res.writeHead(code, (extra_headers || []).concat(
- [["Content-Type", content_type]]));
- res.end();
- }
-
- function doRoute() {
- uri = url_parse(req.url);
- path = uri.pathname;
-
- for (var i = 0, l = routes.length; i < l; i += 1) {
- var route = routes[i];
- if (req.method === route.method) {
- var match = path.match(route.pattern);
- if (match && match[0].length > 0) {
- match.shift();
- match = match.map(function (part) {
- return part ? unescape(part) : part;
- });
- match.unshift(res);
- match.unshift(req);
- if (route.format !== undefined) {
- var body = "";
- req.setEncoding('utf8');
- req.addListener('data', function (chunk) {
- body += chunk;
- });
- req.addListener('end', function () {
- if (route.format === 'json') {
- try {
- body = JSON.parse(unescape(body));
- } catch(e) {
- body = null;
- }
- }
- match.push(body);
- route.handler.apply(null, match);
- });
- return;
- }
- var result = route.handler.apply(null, match);
- switch (typeof result) {
- case "string":
- res.simpleHtml(200, result);
- break;
- case "object":
- res.simpleJson(200, result);
- break;
- }
-
- return;
- }
- }
- }
-
- notFound(req, res);
- }
- doRoute();
-
- });
-
-
- function listen(port, host, callback) {
- port = port || 8080;
-
- if (typeof host === 'undefined' || host == '*')
- host = null;
-
- server.listen(port, host, callback);
-
- if (typeof port === 'number') {
- logger("node-router server instance at http://" + (host || '*') + ":" + port + "/");
- } else {
- logger("node-router server instance at unix:" + port);
- }
- }
-
- function end() {
- return server.end();
- }
-
- // Return a handle to the public facing functions from this closure as the
- // server object.
- return {
- get: get,
- post: post,
- put: put,
- del: del,
- resource: resource,
- resourceController: resourceController,
- listen: listen,
- end: end
- };
-}
-
-
-
-
-exports.staticHandler = function (filename) {
- var body, headers;
- var content_type = mime.getMime(filename)
- var encoding = (content_type.slice(0,4) === "text" ? "utf8" : "binary");
-
- function loadResponseData(req, res, callback) {
- if (body && headers) {
- callback();
- return;
- }
-
- fs.readFile(filename, encoding, function (err, data) {
- if (err) {
- notFound(req, res, "Cannot find file: " + filename);
- return;
- }
- body = data;
- headers = [ [ "Content-Type" , content_type ],
- [ "Content-Length" , body.length ]
- ];
- headers.push(["Cache-Control", "public"]);
-
- callback();
- });
- }
-
- return function (req, res) {
- loadResponseData(req, res, function () {
- res.writeHead(200, headers);
- if (req.method !== "HEAD")
- res.write(body, encoding);
- res.end();
- });
- };
-};
-
-exports.staticDirHandler = function(root, prefix) {
- function loadResponseData(req, res, filename, callback) {
- var content_type = mime.getMime(filename);
- var encoding = (content_type.slice(0,4) === "text" ? "utf8" : "binary");
-
- fs.readFile(filename, encoding, function(err, data) {
- if(err) {
- notFound(req, res, "Cannot find file: " + filename);
- return;
- }
- var headers = [ [ "Content-Type" , content_type ],
- [ "Content-Length" , data.length ],
- [ "Cache-Control" , "public" ]
- ];
- callback(headers, data, encoding);
- });
- }
-
- return function (req, res) {
- // trim off any query/anchor stuff
- var filename = req.url.replace(/[\?|#].*$/, '');
- if (prefix) filename = filename.replace(new RegExp('^'+prefix), '');
- // make sure nobody can explore our local filesystem
- filename = path.join(root, filename.replace(/\.\.+/g, '.'));
- if (filename == root) filename = path.join(root, 'index.html');
- loadResponseData(req, res, filename, function(headers, body, encoding) {
- res.writeHead(200, headers);
- if (req.method !== "HEAD")
- res.write(body, encoding);
- res.end();
- });
- };
-};
-
-
-// Mini mime module for static file serving
-var DEFAULT_MIME = 'application/octet-stream';
-var mime = exports.mime = {
-
- getMime: function getMime(path) {
- var index = path.lastIndexOf(".");
- if (index < 0) {
- return DEFAULT_MIME;
- }
- return mime.TYPES[path.substring(index).toLowerCase()] || DEFAULT_MIME;
- },
-
- TYPES : { ".3gp" : "video/3gpp",
- ".a" : "application/octet-stream",
- ".ai" : "application/postscript",
- ".aif" : "audio/x-aiff",
- ".aiff" : "audio/x-aiff",
- ".asc" : "application/pgp-signature",
- ".asf" : "video/x-ms-asf",
- ".asm" : "text/x-asm",
- ".asx" : "video/x-ms-asf",
- ".atom" : "application/atom+xml",
- ".au" : "audio/basic",
- ".avi" : "video/x-msvideo",
- ".bat" : "application/x-msdownload",
- ".bin" : "application/octet-stream",
- ".bmp" : "image/bmp",
- ".bz2" : "application/x-bzip2",
- ".c" : "text/x-c",
- ".cab" : "application/vnd.ms-cab-compressed",
- ".cc" : "text/x-c",
- ".chm" : "application/vnd.ms-htmlhelp",
- ".class" : "application/octet-stream",
- ".com" : "application/x-msdownload",
- ".conf" : "text/plain",
- ".cpp" : "text/x-c",
- ".crt" : "application/x-x509-ca-cert",
- ".css" : "text/css",
- ".csv" : "text/csv",
- ".cxx" : "text/x-c",
- ".deb" : "application/x-debian-package",
- ".der" : "application/x-x509-ca-cert",
- ".diff" : "text/x-diff",
- ".djv" : "image/vnd.djvu",
- ".djvu" : "image/vnd.djvu",
- ".dll" : "application/x-msdownload",
- ".dmg" : "application/octet-stream",
- ".doc" : "application/msword",
- ".dot" : "application/msword",
- ".dtd" : "application/xml-dtd",
- ".dvi" : "application/x-dvi",
- ".ear" : "application/java-archive",
- ".eml" : "message/rfc822",
- ".eps" : "application/postscript",
- ".exe" : "application/x-msdownload",
- ".f" : "text/x-fortran",
- ".f77" : "text/x-fortran",
- ".f90" : "text/x-fortran",
- ".flv" : "video/x-flv",
- ".for" : "text/x-fortran",
- ".gem" : "application/octet-stream",
- ".gemspec" : "text/x-script.ruby",
- ".gif" : "image/gif",
- ".gz" : "application/x-gzip",
- ".h" : "text/x-c",
- ".hh" : "text/x-c",
- ".htm" : "text/html",
- ".html" : "text/html",
- ".ico" : "image/vnd.microsoft.icon",
- ".ics" : "text/calendar",
- ".ifb" : "text/calendar",
- ".iso" : "application/octet-stream",
- ".jar" : "application/java-archive",
- ".java" : "text/x-java-source",
- ".jnlp" : "application/x-java-jnlp-file",
- ".jpeg" : "image/jpeg",
- ".jpg" : "image/jpeg",
- ".js" : "application/javascript",
- ".json" : "application/json",
- ".log" : "text/plain",
- ".m3u" : "audio/x-mpegurl",
- ".m4v" : "video/mp4",
- ".man" : "text/troff",
- ".mathml" : "application/mathml+xml",
- ".mbox" : "application/mbox",
- ".mdoc" : "text/troff",
- ".me" : "text/troff",
- ".mid" : "audio/midi",
- ".midi" : "audio/midi",
- ".mime" : "message/rfc822",
- ".mml" : "application/mathml+xml",
- ".mng" : "video/x-mng",
- ".mov" : "video/quicktime",
- ".mp3" : "audio/mpeg",
- ".mp4" : "video/mp4",
- ".mp4v" : "video/mp4",
- ".mpeg" : "video/mpeg",
- ".mpg" : "video/mpeg",
- ".ms" : "text/troff",
- ".msi" : "application/x-msdownload",
- ".odp" : "application/vnd.oasis.opendocument.presentation",
- ".ods" : "application/vnd.oasis.opendocument.spreadsheet",
- ".odt" : "application/vnd.oasis.opendocument.text",
- ".ogg" : "application/ogg",
- ".p" : "text/x-pascal",
- ".pas" : "text/x-pascal",
- ".pbm" : "image/x-portable-bitmap",
- ".pdf" : "application/pdf",
- ".pem" : "application/x-x509-ca-cert",
- ".pgm" : "image/x-portable-graymap",
- ".pgp" : "application/pgp-encrypted",
- ".pkg" : "application/octet-stream",
- ".pl" : "text/x-script.perl",
- ".pm" : "text/x-script.perl-module",
- ".png" : "image/png",
- ".pnm" : "image/x-portable-anymap",
- ".ppm" : "image/x-portable-pixmap",
- ".pps" : "application/vnd.ms-powerpoint",
- ".ppt" : "application/vnd.ms-powerpoint",
- ".ps" : "application/postscript",
- ".psd" : "image/vnd.adobe.photoshop",
- ".py" : "text/x-script.python",
- ".qt" : "video/quicktime",
- ".ra" : "audio/x-pn-realaudio",
- ".rake" : "text/x-script.ruby",
- ".ram" : "audio/x-pn-realaudio",
- ".rar" : "application/x-rar-compressed",
- ".rb" : "text/x-script.ruby",
- ".rdf" : "application/rdf+xml",
- ".roff" : "text/troff",
- ".rpm" : "application/x-redhat-package-manager",
- ".rss" : "application/rss+xml",
- ".rtf" : "application/rtf",
- ".ru" : "text/x-script.ruby",
- ".s" : "text/x-asm",
- ".sgm" : "text/sgml",
- ".sgml" : "text/sgml",
- ".sh" : "application/x-sh",
- ".sig" : "application/pgp-signature",
- ".snd" : "audio/basic",
- ".so" : "application/octet-stream",
- ".svg" : "image/svg+xml",
- ".svgz" : "image/svg+xml",
- ".swf" : "application/x-shockwave-flash",
- ".t" : "text/troff",
- ".tar" : "application/x-tar",
- ".tbz" : "application/x-bzip-compressed-tar",
- ".tci" : "application/x-topcloud",
- ".tcl" : "application/x-tcl",
- ".tex" : "application/x-tex",
- ".texi" : "application/x-texinfo",
- ".texinfo" : "application/x-texinfo",
- ".text" : "text/plain",
- ".tif" : "image/tiff",
- ".tiff" : "image/tiff",
- ".torrent" : "application/x-bittorrent",
- ".tr" : "text/troff",
- ".ttf" : "application/x-font-ttf",
- ".txt" : "text/plain",
- ".vcf" : "text/x-vcard",
- ".vcs" : "text/x-vcalendar",
- ".vrml" : "model/vrml",
- ".war" : "application/java-archive",
- ".wav" : "audio/x-wav",
- ".wma" : "audio/x-ms-wma",
- ".wmv" : "video/x-ms-wmv",
- ".wmx" : "video/x-ms-wmx",
- ".wrl" : "model/vrml",
- ".wsdl" : "application/wsdl+xml",
- ".xbm" : "image/x-xbitmap",
- ".xhtml" : "application/xhtml+xml",
- ".xls" : "application/vnd.ms-excel",
- ".xml" : "application/xml",
- ".xpm" : "image/x-xpixmap",
- ".xsl" : "application/xml",
- ".xslt" : "application/xslt+xml",
- ".yaml" : "text/yaml",
- ".yml" : "text/yaml",
- ".zip" : "application/zip"
- }
-};
View
3  package.json
@@ -2,5 +2,8 @@
"name": "fuck-yeah",
"version": "0.0.1",
"dependencies": {
+ "imagemagick": "0.1.2",
+ "request": "2.1.1",
+ "node-router": "https://github.com/creationix/node-router/tarball/master"
}
}
View
447 request.js
@@ -1,447 +0,0 @@
-// Copyright 2010-2011 Mikeal Rogers
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-var http = require('http')
- , https = false
- , tls = false
- , url = require('url')
- , util = require('util')
- , stream = require('stream')
- , qs = require('querystring')
- , mimetypes = require('./mimetypes')
- ;
-
-try {
- https = require('https')
-} catch (e) {}
-
-try {
- tls = require('tls')
-} catch (e) {}
-
-function toBase64 (str) {
- return (new Buffer(str || "", "ascii")).toString("base64")
-}
-
-// Hacky fix for pre-0.4.4 https
-if (https && !https.Agent) {
- https.Agent = function (options) {
- http.Agent.call(this, options)
- }
- util.inherits(https.Agent, http.Agent)
- https.Agent.prototype._getConnection = function(host, port, cb) {
- var s = tls.connect(port, host, this.options, function() {
- // do other checks here?
- if (cb) cb()
- })
- return s
- }
-}
-
-function isReadStream (rs) {
- if (rs.readable && rs.path && rs.mode) {
- return true
- }
-}
-
-function copy (obj) {
- var o = {}
- for (i in obj) o[i] = obj[i]
- return o
-}
-
-var isUrl = /^https?:/
-
-var globalPool = {}
-
-function Request (options) {
- stream.Stream.call(this)
- this.readable = true
- this.writable = true
-
- if (typeof options === 'string') {
- options = {uri:options}
- }
-
- for (i in options) {
- this[i] = options[i]
- }
- if (!this.pool) this.pool = globalPool
- this.dests = []
- this.__isRequestRequest = true
-}
-util.inherits(Request, stream.Stream)
-Request.prototype.getAgent = function (host, port) {
- if (!this.pool[host+':'+port]) {
- this.pool[host+':'+port] = new this.httpModule.Agent({host:host, port:port})
- }
- return this.pool[host+':'+port]
-}
-Request.prototype.request = function () {
- var options = this
- if (options.url) {
- // People use this property instead all the time so why not just support it.
- options.uri = options.url
- delete options.url
- }
-
- if (!options.uri) {
- throw new Error("options.uri is a required argument")
- } else {
- if (typeof options.uri == "string") options.uri = url.parse(options.uri)
- }
- if (options.proxy) {
- if (typeof options.proxy == 'string') options.proxy = url.parse(options.proxy)
- }
-
- options._redirectsFollowed = options._redirectsFollowed || 0
- options.maxRedirects = (options.maxRedirects !== undefined) ? options.maxRedirects : 10
- options.followRedirect = (options.followRedirect !== undefined) ? options.followRedirect : true
-
- options.headers = options.headers ? copy(options.headers) : {}
-
- var setHost = false
- if (!options.headers.host) {
- options.headers.host = options.uri.hostname
- if (options.uri.port) {
- if ( !(options.uri.port === 80 && options.uri.protocol === 'http:') &&
- !(options.uri.port === 443 && options.uri.protocol === 'https:') )
- options.headers.host += (':'+options.uri.port)
- }
- setHost = true
- }
-
- if (!options.uri.pathname) {options.uri.pathname = '/'}
- if (!options.uri.port) {
- if (options.uri.protocol == 'http:') {options.uri.port = 80}
- else if (options.uri.protocol == 'https:') {options.uri.port = 443}
- }
-
- if (options.bodyStream || options.responseBodyStream) {
- console.error('options.bodyStream and options.responseBodyStream is deprecated. You should now send the request object to stream.pipe()')
- this.pipe(options.responseBodyStream || options.bodyStream)
- }
-
- if (options.proxy) {
- options.port = options.proxy.port
- options.host = options.proxy.hostname
- } else {
- options.port = options.uri.port
- options.host = options.uri.hostname
- }
-
- if (options.onResponse === true) {
- options.onResponse = options.callback
- delete options.callback
- }
-
- var clientErrorHandler = function (error) {
- if (setHost) delete options.headers.host
- options.emit('error', error)
- }
- if (options.onResponse) options.on('error', function (e) {options.onResponse(e)})
- if (options.callback) options.on('error', function (e) {options.callback(e)})
-
-
- if (options.uri.auth && !options.headers.authorization) {
- options.headers.authorization = "Basic " + toBase64(options.uri.auth.split(':').map(function(item){ return qs.unescape(item)}).join(':'))
- }
- if (options.proxy && options.proxy.auth && !options.headers['proxy-authorization']) {
- options.headers.authorization = "Basic " + toBase64(options.uri.auth.split(':').map(function(item){ return qs.unescape(item)}).join(':'))
- }
-
- options.path = options.uri.href.replace(options.uri.protocol + '//' + options.uri.host, '')
- if (options.path.length === 0) options.path = '/'
-
- if (options.proxy) options.path = (options.uri.protocol + '//' + options.uri.host + options.path)
-
- if (options.json) {
- options.headers['content-type'] = 'application/json'
- if (typeof options.json === 'boolean') {
- if (typeof options.body === 'object') options.body = JSON.stringify(options.body)
- } else {
- options.body = JSON.stringify(options.json)
- }
-
- } else if (options.multipart) {
- options.body = ''
- options.headers['content-type'] = 'multipart/related;boundary="frontier"'
- if (!options.multipart.forEach) throw new Error('Argument error, options.multipart.')
-
- options.multipart.forEach(function (part) {
- var body = part.body
- if(!body) throw Error('Body attribute missing in multipart.')
- delete part.body
- options.body += '--frontier\r\n'
- Object.keys(part).forEach(function(key){
- options.body += key + ': ' + part[key] + '\r\n'
- })
- options.body += '\r\n' + body + '\r\n'
- })
- options.body += '--frontier--'
- }
-
- if (options.body) {
- if (!Buffer.isBuffer(options.body)) {
- options.body = new Buffer(options.body)
- }
- if (options.body.length) {
- options.headers['content-length'] = options.body.length
- } else {
- throw new Error('Argument error, options.body.')
- }
- }
-
- options.httpModule =
- {"http:":http, "https:":https}[options.proxy ? options.proxy.protocol : options.uri.protocol]
-
- if (!options.httpModule) throw new Error("Invalid protocol")
-
- if (options.pool === false) {
- options.agent = false
- } else {
- if (options.maxSockets) {
- // Don't use our pooling if node has the refactored client
- options.agent = options.httpModule.globalAgent || options.getAgent(options.host, options.port)
- options.agent.maxSockets = options.maxSockets
- }
- if (options.pool.maxSockets) {
- // Don't use our pooling if node has the refactored client
- options.agent = options.httpModule.globalAgent || options.getAgent(options.host, options.port)
- options.agent.maxSockets = options.pool.maxSockets
- }
- }
-
- options.start = function () {
- options._started = true
- options.method = options.method || 'GET'
-
- options.req = options.httpModule.request(options, function (response) {
- options.response = response
- response.request = options
- if (setHost) delete options.headers.host
- if (options.timeout && options.timeoutTimer) clearTimeout(options.timeoutTimer)
-
- if (response.statusCode >= 300 &&
- response.statusCode < 400 &&
- options.followRedirect &&
- options.method !== 'PUT' &&
- options.method !== 'POST' &&
- response.headers.location) {
- if (options._redirectsFollowed >= options.maxRedirects) {
- options.emit('error', new Error("Exceeded maxRedirects. Probably stuck in a redirect loop."))
- return
- }
- options._redirectsFollowed += 1
-
- if (!isUrl.test(response.headers.location)) {
- response.headers.location = url.resolve(options.uri.href, response.headers.location)
- }
- options.uri = response.headers.location
- delete options.req
- delete options.agent
- delete options._started
- if (options.headers) {
- delete options.headers.host
- }
- request(options, options.callback)
- return // Ignore the rest of the response
- } else {
- options._redirectsFollowed = 0
- // Be a good stream and emit end when the response is finished.
- // Hack to emit end on close because of a core bug that never fires end
- response.on('close', function () {
- if (!options._ended) options.response.emit('end')
- })
-
- if (options.encoding) {
- if (options.dests.length !== 0) {
- console.error("Ingoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.")
- } else {
- response.setEncoding(options.encoding)
- }
- }
-
- options.dests.forEach(function (dest) {
- if (dest.headers) {
- dest.headers['content-type'] = response.headers['content-type']
- if (response.headers['content-length']) {
- dest.headers['content-length'] = response.headers['content-length']
- }
- }
- if (dest.setHeader) {
- for (i in response.headers) {
- dest.setHeader(i, response.headers[i])
- }
- dest.statusCode = response.statusCode
- }
- if (options.pipefilter) options.pipefilter(response, dest)
- })
-
- response.on("data", function (chunk) {options.emit("data", chunk)})
- response.on("end", function (chunk) {
- options._ended = true
- options.emit("end", chunk)
- })
- response.on("close", function () {options.emit("close")})
-
- if (options.onResponse) {
- options.onResponse(null, response)
- }
- if (options.callback) {
- var buffer = ''
- options.on("data", function (chunk) {
- buffer += chunk
- })
- options.on("end", function () {
- response.body = buffer
- if (options.json) {
- try {
- response.body = JSON.parse(response.body)
- } catch (e) {}
- }
- options.callback(null, response, response.body)
- })
- }
- }
- })
-
- if (options.timeout) {
- options.timeoutTimer = setTimeout(function() {
- options.req.abort()
- var e = new Error("ETIMEDOUT")
- e.code = "ETIMEDOUT"
- options.emit("error", e)
- }, options.timeout)
- }
-
- options.req.on('error', clientErrorHandler)
- }
-
- options.once('pipe', function (src) {
- if (options.ntick) throw new Error("You cannot pipe to this stream after the first nextTick() after creation of the request stream.")
- options.src = src
- if (isReadStream(src)) {
- if (!options.headers['content-type'] && !options.headers['Content-Type'])
- options.headers['content-type'] = mimetypes.lookup(src.path.slice(src.path.lastIndexOf('.')+1))
- } else {
- if (src.headers) {
- for (i in src.headers) {
- if (!options.headers[i]) {
- options.headers[i] = src.headers[i]
- }
- }
- }
- if (src.method && !options.method) {
- options.method = src.method
- }
- }
-
- options.on('pipe', function () {
- console.error("You have already piped to this stream. Pipeing twice is likely to break the request.")
- })
- })
-
- process.nextTick(function () {
- if (options.body) {
- options.write(options.body)
- options.end()
- } else if (options.requestBodyStream) {
- console.warn("options.requestBodyStream is deprecated, please pass the request object to stream.pipe.")
- options.requestBodyStream.pipe(options)
- } else if (!options.src) {
- options.end()
- }
- options.ntick = true
- })
-}
-Request.prototype.pipe = function (dest) {
- if (this.response) throw new Error("You cannot pipe after the response event.")
- this.dests.push(dest)
- stream.Stream.prototype.pipe.call(this, dest)
- return dest
-}
-Request.prototype.write = function () {
- if (!this._started) this.start()
- if (!this.req) throw new Error("This request has been piped before http.request() was called.")
- this.req.write.apply(this.req, arguments)
-}
-Request.prototype.end = function () {
- if (!this._started) this.start()
- if (!this.req) throw new Error("This request has been piped before http.request() was called.")
- this.req.end.apply(this.req, arguments)
-}
-Request.prototype.pause = function () {
- if (!this.response) throw new Error("This request has been piped before http.request() was called.")
- this.response.pause.apply(this.response, arguments)
-}
-Request.prototype.resume = function () {
- if (!this.response) throw new Error("This request has been piped before http.request() was called.")
- this.response.resume.apply(this.response, arguments)
-}
-
-function request (options, callback) {
- if (typeof options === 'string') options = {uri:options}
- if (callback) options.callback = callback
- var r = new Request(options)
- r.request()
- return r
-}
-
-module.exports = request
-
-request.defaults = function (options) {
- var def = function (method) {
- var d = function (opts, callback) {
- if (typeof opts === 'string') opts = {uri:opts}
- for (i in options) {
- if (opts[i] === undefined) opts[i] = options[i]
- }
- return method(opts, callback)
- }
- return d
- }
- de = def(request)
- de.get = def(request.get)
- de.post = def(request.post)
- de.put = def(request.put)
- de.head = def(request.head)
- de.del = def(request.del)
- return de
-}
-
-request.get = request
-request.post = function (options, callback) {
- if (typeof options === 'string') options = {uri:options}
- options.method = 'POST'
- return request(options, callback)
-}
-request.put = function (options, callback) {
- if (typeof options === 'string') options = {uri:options}
- options.method = 'PUT'
- return request(options, callback)
-}
-request.head = function (options, callback) {
- if (typeof options === 'string') options = {uri:options}
- options.method = 'HEAD'
- if (options.body || options.requestBodyStream || options.json || options.multipart) {
- throw new Error("HTTP HEAD requests MUST NOT include a request body.")
- }
- return request(options, callback)
-}
-request.del = function (options, callback) {
- if (typeof options === 'string') options = {uri:options}
- options.method = 'DELETE'
- return request(options, callback)
-}
Please sign in to comment.
Something went wrong with that request. Please try again.