Commit f064c792 authored by Muddsair Sharif's avatar Muddsair Sharif
Browse files

Initial commit

parents
Pipeline #8 canceled with stages
module.exports = exports = abbrev.abbrev = abbrev
abbrev.monkeyPatch = monkeyPatch
function monkeyPatch () {
Object.defineProperty(Array.prototype, 'abbrev', {
value: function () { return abbrev(this) },
enumerable: false, configurable: true, writable: true
})
Object.defineProperty(Object.prototype, 'abbrev', {
value: function () { return abbrev(Object.keys(this)) },
enumerable: false, configurable: true, writable: true
})
}
function abbrev (list) {
if (arguments.length !== 1 || !Array.isArray(list)) {
list = Array.prototype.slice.call(arguments, 0)
}
for (var i = 0, l = list.length, args = [] ; i < l ; i ++) {
args[i] = typeof list[i] === "string" ? list[i] : String(list[i])
}
// sort them lexicographically, so that they're next to their nearest kin
args = args.sort(lexSort)
// walk through each, seeing how much it has in common with the next and previous
var abbrevs = {}
, prev = ""
for (var i = 0, l = args.length ; i < l ; i ++) {
var current = args[i]
, next = args[i + 1] || ""
, nextMatches = true
, prevMatches = true
if (current === next) continue
for (var j = 0, cl = current.length ; j < cl ; j ++) {
var curChar = current.charAt(j)
nextMatches = nextMatches && curChar === next.charAt(j)
prevMatches = prevMatches && curChar === prev.charAt(j)
if (!nextMatches && !prevMatches) {
j ++
break
}
}
prev = current
if (j === cl) {
abbrevs[current] = current
continue
}
for (var a = current.substr(0, j) ; j <= cl ; j ++) {
abbrevs[a] = current
a += current.charAt(j)
}
}
return abbrevs
}
function lexSort (a, b) {
return a === b ? 0 : a > b ? 1 : -1
}
{
"_from": "abbrev@1",
"_id": "abbrev@1.1.1",
"_inBundle": false,
"_integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==",
"_location": "/abbrev",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "abbrev@1",
"name": "abbrev",
"escapedName": "abbrev",
"rawSpec": "1",
"saveSpec": null,
"fetchSpec": "1"
},
"_requiredBy": [
"/nopt"
],
"_resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz",
"_shasum": "f8f2c887ad10bf67f634f005b6987fed3179aac8",
"_spec": "abbrev@1",
"_where": "/Users/Chorthip/Documents/GitKraken/nasaproject/node_modules/nopt",
"author": {
"name": "Isaac Z. Schlueter",
"email": "i@izs.me"
},
"bugs": {
"url": "https://github.com/isaacs/abbrev-js/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Like ruby's abbrev module, but in js",
"devDependencies": {
"tap": "^10.1"
},
"files": [
"abbrev.js"
],
"homepage": "https://github.com/isaacs/abbrev-js#readme",
"license": "ISC",
"main": "abbrev.js",
"name": "abbrev",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/isaacs/abbrev-js.git"
},
"scripts": {
"postpublish": "git push origin --all; git push origin --tags",
"postversion": "npm publish",
"preversion": "npm test",
"test": "tap test.js --100"
},
"version": "1.1.1"
}
1.3.3 / 2016-05-02
==================
* deps: mime-types@~2.1.11
- deps: mime-db@~1.23.0
* deps: negotiator@0.6.1
- perf: improve `Accept` parsing speed
- perf: improve `Accept-Charset` parsing speed
- perf: improve `Accept-Encoding` parsing speed
- perf: improve `Accept-Language` parsing speed
1.3.2 / 2016-03-08
==================
* deps: mime-types@~2.1.10
- Fix extension of `application/dash+xml`
- Update primary extension for `audio/mp4`
- deps: mime-db@~1.22.0
1.3.1 / 2016-01-19
==================
* deps: mime-types@~2.1.9
- deps: mime-db@~1.21.0
1.3.0 / 2015-09-29
==================
* deps: mime-types@~2.1.7
- deps: mime-db@~1.19.0
* deps: negotiator@0.6.0
- Fix including type extensions in parameters in `Accept` parsing
- Fix parsing `Accept` parameters with quoted equals
- Fix parsing `Accept` parameters with quoted semicolons
- Lazy-load modules from main entry point
- perf: delay type concatenation until needed
- perf: enable strict mode
- perf: hoist regular expressions
- perf: remove closures getting spec properties
- perf: remove a closure from media type parsing
- perf: remove property delete from media type parsing
1.2.13 / 2015-09-06
===================
* deps: mime-types@~2.1.6
- deps: mime-db@~1.18.0
1.2.12 / 2015-07-30
===================
* deps: mime-types@~2.1.4
- deps: mime-db@~1.16.0
1.2.11 / 2015-07-16
===================
* deps: mime-types@~2.1.3
- deps: mime-db@~1.15.0
1.2.10 / 2015-07-01
===================
* deps: mime-types@~2.1.2
- deps: mime-db@~1.14.0
1.2.9 / 2015-06-08
==================
* deps: mime-types@~2.1.1
- perf: fix deopt during mapping
1.2.8 / 2015-06-07
==================
* deps: mime-types@~2.1.0
- deps: mime-db@~1.13.0
* perf: avoid argument reassignment & argument slice
* perf: avoid negotiator recursive construction
* perf: enable strict mode
* perf: remove unnecessary bitwise operator
1.2.7 / 2015-05-10
==================
* deps: negotiator@0.5.3
- Fix media type parameter matching to be case-insensitive
1.2.6 / 2015-05-07
==================
* deps: mime-types@~2.0.11
- deps: mime-db@~1.9.1
* deps: negotiator@0.5.2
- Fix comparing media types with quoted values
- Fix splitting media types with quoted commas
1.2.5 / 2015-03-13
==================
* deps: mime-types@~2.0.10
- deps: mime-db@~1.8.0
1.2.4 / 2015-02-14
==================
* Support Node.js 0.6
* deps: mime-types@~2.0.9
- deps: mime-db@~1.7.0
* deps: negotiator@0.5.1
- Fix preference sorting to be stable for long acceptable lists
1.2.3 / 2015-01-31
==================
* deps: mime-types@~2.0.8
- deps: mime-db@~1.6.0
1.2.2 / 2014-12-30
==================
* deps: mime-types@~2.0.7
- deps: mime-db@~1.5.0
1.2.1 / 2014-12-30
==================
* deps: mime-types@~2.0.5
- deps: mime-db@~1.3.1
1.2.0 / 2014-12-19
==================
* deps: negotiator@0.5.0
- Fix list return order when large accepted list
- Fix missing identity encoding when q=0 exists
- Remove dynamic building of Negotiator class
1.1.4 / 2014-12-10
==================
* deps: mime-types@~2.0.4
- deps: mime-db@~1.3.0
1.1.3 / 2014-11-09
==================
* deps: mime-types@~2.0.3
- deps: mime-db@~1.2.0
1.1.2 / 2014-10-14
==================
* deps: negotiator@0.4.9
- Fix error when media type has invalid parameter
1.1.1 / 2014-09-28
==================
* deps: mime-types@~2.0.2
- deps: mime-db@~1.1.0
* deps: negotiator@0.4.8
- Fix all negotiations to be case-insensitive
- Stable sort preferences of same quality according to client order
1.1.0 / 2014-09-02
==================
* update `mime-types`
1.0.7 / 2014-07-04
==================
* Fix wrong type returned from `type` when match after unknown extension
1.0.6 / 2014-06-24
==================
* deps: negotiator@0.4.7
1.0.5 / 2014-06-20
==================
* fix crash when unknown extension given
1.0.4 / 2014-06-19
==================
* use `mime-types`
1.0.3 / 2014-06-11
==================
* deps: negotiator@0.4.6
- Order by specificity when quality is the same
1.0.2 / 2014-05-29
==================
* Fix interpretation when header not in request
* deps: pin negotiator@0.4.5
1.0.1 / 2014-01-18
==================
* Identity encoding isn't always acceptable
* deps: negotiator@~0.4.0
1.0.0 / 2013-12-27
==================
* Genesis
(The MIT License)
Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
Copyright (c) 2015 Douglas Christopher Wilson <doug@somethingdoug.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.
# accepts
[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]
[![Node.js Version][node-version-image]][node-version-url]
[![Build Status][travis-image]][travis-url]
[![Test Coverage][coveralls-image]][coveralls-url]
Higher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator). Extracted from [koa](https://www.npmjs.com/package/koa) for general use.
In addition to negotiator, it allows:
- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])` as well as `('text/html', 'application/json')`.
- Allows type shorthands such as `json`.
- Returns `false` when no types match
- Treats non-existent headers as `*`
## Installation
```sh
npm install accepts
```
## API
```js
var accepts = require('accepts')
```
### accepts(req)
Create a new `Accepts` object for the given `req`.
#### .charset(charsets)
Return the first accepted charset. If nothing in `charsets` is accepted,
then `false` is returned.
#### .charsets()
Return the charsets that the request accepts, in the order of the client's
preference (most preferred first).
#### .encoding(encodings)
Return the first accepted encoding. If nothing in `encodings` is accepted,
then `false` is returned.
#### .encodings()
Return the encodings that the request accepts, in the order of the client's
preference (most preferred first).
#### .language(languages)
Return the first accepted language. If nothing in `languages` is accepted,
then `false` is returned.
#### .languages()
Return the languages that the request accepts, in the order of the client's
preference (most preferred first).
#### .type(types)
Return the first accepted type (and it is returned as the same text as what
appears in the `types` array). If nothing in `types` is accepted, then `false`
is returned.
The `types` array can contain full MIME types or file extensions. Any value
that is not a full MIME types is passed to `require('mime-types').lookup`.
#### .types()
Return the types that the request accepts, in the order of the client's
preference (most preferred first).
## Examples
### Simple type negotiation
This simple example shows how to use `accepts` to return a different typed
respond body based on what the client wants to accept. The server lists it's
preferences in order and will get back the best match between the client and
server.
```js
var accepts = require('accepts')
var http = require('http')
function app(req, res) {
var accept = accepts(req)
// the order of this list is significant; should be server preferred order
switch(accept.type(['json', 'html'])) {
case 'json':
res.setHeader('Content-Type', 'application/json')
res.write('{"hello":"world!"}')
break
case 'html':
res.setHeader('Content-Type', 'text/html')
res.write('<b>hello, world!</b>')
break
default:
// the fallback is text/plain, so no need to specify it above
res.setHeader('Content-Type', 'text/plain')
res.write('hello, world!')
break
}
res.end()
}
http.createServer(app).listen(3000)
```
You can test this out with the cURL program:
```sh
curl -I -H'Accept: text/html' http://localhost:3000/
```
## License
[MIT](LICENSE)
[npm-image]: https://img.shields.io/npm/v/accepts.svg
[npm-url]: https://npmjs.org/package/accepts
[node-version-image]: https://img.shields.io/node/v/accepts.svg
[node-version-url]: http://nodejs.org/download/
[travis-image]: https://img.shields.io/travis/jshttp/accepts/master.svg
[travis-url]: https://travis-ci.org/jshttp/accepts
[coveralls-image]: https://img.shields.io/coveralls/jshttp/accepts/master.svg
[coveralls-url]: https://coveralls.io/r/jshttp/accepts
[downloads-image]: https://img.shields.io/npm/dm/accepts.svg
[downloads-url]: https://npmjs.org/package/accepts
/*!
* accepts
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var Negotiator = require('negotiator')
var mime = require('mime-types')
/**
* Module exports.
* @public
*/
module.exports = Accepts
/**
* Create a new Accepts object for the given req.
*
* @param {object} req
* @public
*/
function Accepts(req) {
if (!(this instanceof Accepts))
return new Accepts(req)
this.headers = req.headers
this.negotiator = new Negotiator(req)
}
/**
* Check if the given `type(s)` is acceptable, returning
* the best match when true, otherwise `undefined`, in which
* case you should respond with 406 "Not Acceptable".
*
* The `type` value may be a single mime type string
* such as "application/json", the extension name
* such as "json" or an array `["json", "html", "text/plain"]`. When a list
* or array is given the _best_ match, if any is returned.
*
* Examples:
*
* // Accept: text/html
* this.types('html');
* // => "html"
*
* // Accept: text/*, application/json
* this.types('html');
* // => "html"
* this.types('text/html');
* // => "text/html"
* this.types('json', 'text');
* // => "json"
* this.types('application/json');
* // => "application/json"
*
* // Accept: text/*, application/json
* this.types('image/png');
* this.types('png');
* // => undefined
*
* // Accept: text/*;q=.5, application/json
* this.types(['html', 'json']);
* this.types('html', 'json');
* // => "json"
*
* @param {String|Array} types...
* @return {String|Array|Boolean}
* @public
*/
Accepts.prototype.type =
Accepts.prototype.types = function (types_) {
var types = types_
// support flattened arguments
if (types && !Array.isArray(types)) {
types = new Array(arguments.length)
for (var i = 0; i < types.length; i++) {
types[i] = arguments[i]
}
}
// no types, return all requested types
if (!types || types.length === 0) {
return this.negotiator.mediaTypes()
}
if (!this.headers.accept) return types[0];
var mimes = types.map(extToMime);
var accepts = this.negotiator.mediaTypes(mimes.filter(validMime));
var first = accepts[0];
if (!first) return false;
return types[mimes.indexOf(first)];
}
/**
* Return accepted encodings or best fit based on `encodings`.
*
* Given `Accept-Encoding: gzip, deflate`
* an array sorted by quality is returned:
*
* ['gzip', 'deflate']
*
* @param {String|Array} encodings...
* @return {String|Array}
* @public
*/
Accepts.prototype.encoding =
Accepts.prototype.encodings = function (encodings_) {
var encodings = encodings_
// support flattened arguments
if (encodings && !Array.isArray(encodings)) {
encodings = new Array(arguments.length)
for (var i = 0; i < encodings.length; i++) {
encodings[i] = arguments[i]
}
}
// no encodings, return all requested encodings
if (!encodings || encodings.length === 0) {
return this.negotiator.encodings()
}
return this.negotiator.encodings(encodings)[0] || false
}
/**
* Return accepted charsets or best fit based on `charsets`.
*
* Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5`
* an array sorted by quality is returned:
*
* ['utf-8', 'utf-7', 'iso-8859-1']
*
* @param {String|Array} charsets...
* @return {String|Array}
* @public
*/
Accepts.prototype.charset =
Accepts.prototype.charsets = function (charsets_) {
var charsets = charsets_
// support flattened arguments
if (charsets && !Array.isArray(charsets)) {
charsets = new Array(arguments.length)
for (var i = 0; i < charsets.length; i++) {
charsets[i] = arguments[i]
}
}
// no charsets, return all requested charsets
if (!charsets || charsets.length === 0) {
return this.negotiator.charsets()
}
return this.negotiator.charsets(charsets)[0] || false
}
/**
* Return accepted languages or best fit based on `langs`.
*
* Given `Accept-Language: en;q=0.8, es, pt`
* an array sorted by quality is returned:
*
* ['es', 'pt', 'en']
*
* @param {String|Array} langs...
* @return {Array|String}
* @public
*/
Accepts.prototype.lang =
Accepts.prototype.langs =
Accepts.prototype.language =
Accepts.prototype.languages = function (languages_) {
var languages = languages_
// support flattened arguments
if (languages && !Array.isArray(languages)) {
languages = new Array(arguments.length)
for (var i = 0; i < languages.length; i++) {
languages[i] = arguments[i]
}
}
// no languages, return all requested languages
if (!languages || languages.length === 0) {
return this.negotiator.languages()
}
return this.negotiator.languages(languages)[0] || false
}
/**
* Convert extnames to mime.
*
* @param {String} type
* @return {String}
* @private
*/
function extToMime(type) {
return type.indexOf('/') === -1
? mime.lookup(type)
: type
}
/**
* Check if mime is valid.
*
* @param {String} type
* @return {String}
* @private
*/
function validMime(type) {
return typeof type === 'string';
}
{
"_args": [
[
{
"raw": "accepts@~1.3.3",
"scope": null,
"escapedName": "accepts",
"name": "accepts",
"rawSpec": "~1.3.3",
"spec": ">=1.3.3 <1.4.0",
"type": "range"
},
"C:\\Users\\Giuliano\\Desktop\\nasaproject\\node_modules\\express"
]
],
"_from": "accepts@>=1.3.3 <1.4.0",
"_id": "accepts@1.3.3",
"_inCache": true,
"_location": "/accepts",
"_nodeVersion": "4.4.3",
"_npmOperationalInternal": {
"host": "packages-16-east.internal.npmjs.com",
"tmp": "tmp/accepts-1.3.3.tgz_1462251932032_0.7092335098423064"
},
"_npmUser": {
"name": "dougwilson",
"email": "doug@somethingdoug.com"
},
"_npmVersion": "2.15.1",
"_phantomChildren": {},
"_requested": {
"raw": "accepts@~1.3.3",
"scope": null,
"escapedName": "accepts",
"name": "accepts",
"rawSpec": "~1.3.3",
"spec": ">=1.3.3 <1.4.0",
"type": "range"
},
"_requiredBy": [
"/express"
],
"_resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.3.tgz",
"_shasum": "c3ca7434938648c3e0d9c1e328dd68b622c284ca",
"_shrinkwrap": null,
"_spec": "accepts@~1.3.3",
"_where": "C:\\Users\\Giuliano\\Desktop\\nasaproject\\node_modules\\express",
"bugs": {
"url": "https://github.com/jshttp/accepts/issues"
},
"contributors": [
{
"name": "Douglas Christopher Wilson",
"email": "doug@somethingdoug.com"
},
{
"name": "Jonathan Ong",
"email": "me@jongleberry.com",
"url": "http://jongleberry.com"
}
],
"dependencies": {
"mime-types": "~2.1.11",
"negotiator": "0.6.1"
},
"description": "Higher-level content negotiation",
"devDependencies": {
"istanbul": "0.4.3",
"mocha": "~1.21.5"
},
"directories": {},
"dist": {
"shasum": "c3ca7434938648c3e0d9c1e328dd68b622c284ca",
"tarball": "https://registry.npmjs.org/accepts/-/accepts-1.3.3.tgz"
},
"engines": {
"node": ">= 0.6"
},
"files": [
"LICENSE",
"HISTORY.md",
"index.js"
],
"gitHead": "3e925b1e65ed7da2798849683d49814680dfa426",
"homepage": "https://github.com/jshttp/accepts#readme",
"keywords": [
"content",
"negotiation",
"accept",
"accepts"
],
"license": "MIT",
"maintainers": [
{
"name": "dougwilson",
"email": "doug@somethingdoug.com"
}
],
"name": "accepts",
"optionalDependencies": {},
"readme": "# accepts\n\n[![NPM Version][npm-image]][npm-url]\n[![NPM Downloads][downloads-image]][downloads-url]\n[![Node.js Version][node-version-image]][node-version-url]\n[![Build Status][travis-image]][travis-url]\n[![Test Coverage][coveralls-image]][coveralls-url]\n\nHigher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator). Extracted from [koa](https://www.npmjs.com/package/koa) for general use.\n\nIn addition to negotiator, it allows:\n\n- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])` as well as `('text/html', 'application/json')`.\n- Allows type shorthands such as `json`.\n- Returns `false` when no types match\n- Treats non-existent headers as `*`\n\n## Installation\n\n```sh\nnpm install accepts\n```\n\n## API\n\n```js\nvar accepts = require('accepts')\n```\n\n### accepts(req)\n\nCreate a new `Accepts` object for the given `req`.\n\n#### .charset(charsets)\n\nReturn the first accepted charset. If nothing in `charsets` is accepted,\nthen `false` is returned.\n\n#### .charsets()\n\nReturn the charsets that the request accepts, in the order of the client's\npreference (most preferred first).\n\n#### .encoding(encodings)\n\nReturn the first accepted encoding. If nothing in `encodings` is accepted,\nthen `false` is returned.\n\n#### .encodings()\n\nReturn the encodings that the request accepts, in the order of the client's\npreference (most preferred first).\n\n#### .language(languages)\n\nReturn the first accepted language. If nothing in `languages` is accepted,\nthen `false` is returned.\n\n#### .languages()\n\nReturn the languages that the request accepts, in the order of the client's\npreference (most preferred first).\n\n#### .type(types)\n\nReturn the first accepted type (and it is returned as the same text as what\nappears in the `types` array). If nothing in `types` is accepted, then `false`\nis returned.\n\nThe `types` array can contain full MIME types or file extensions. Any value\nthat is not a full MIME types is passed to `require('mime-types').lookup`.\n\n#### .types()\n\nReturn the types that the request accepts, in the order of the client's\npreference (most preferred first).\n\n## Examples\n\n### Simple type negotiation\n\nThis simple example shows how to use `accepts` to return a different typed\nrespond body based on what the client wants to accept. The server lists it's\npreferences in order and will get back the best match between the client and\nserver.\n\n```js\nvar accepts = require('accepts')\nvar http = require('http')\n\nfunction app(req, res) {\n var accept = accepts(req)\n\n // the order of this list is significant; should be server preferred order\n switch(accept.type(['json', 'html'])) {\n case 'json':\n res.setHeader('Content-Type', 'application/json')\n res.write('{\"hello\":\"world!\"}')\n break\n case 'html':\n res.setHeader('Content-Type', 'text/html')\n res.write('<b>hello, world!</b>')\n break\n default:\n // the fallback is text/plain, so no need to specify it above\n res.setHeader('Content-Type', 'text/plain')\n res.write('hello, world!')\n break\n }\n\n res.end()\n}\n\nhttp.createServer(app).listen(3000)\n```\n\nYou can test this out with the cURL program:\n```sh\ncurl -I -H'Accept: text/html' http://localhost:3000/\n```\n\n## License\n\n[MIT](LICENSE)\n\n[npm-image]: https://img.shields.io/npm/v/accepts.svg\n[npm-url]: https://npmjs.org/package/accepts\n[node-version-image]: https://img.shields.io/node/v/accepts.svg\n[node-version-url]: http://nodejs.org/download/\n[travis-image]: https://img.shields.io/travis/jshttp/accepts/master.svg\n[travis-url]: https://travis-ci.org/jshttp/accepts\n[coveralls-image]: https://img.shields.io/coveralls/jshttp/accepts/master.svg\n[coveralls-url]: https://coveralls.io/r/jshttp/accepts\n[downloads-image]: https://img.shields.io/npm/dm/accepts.svg\n[downloads-url]: https://npmjs.org/package/accepts\n",
"readmeFilename": "README.md",
"repository": {
"type": "git",
"url": "git+https://github.com/jshttp/accepts.git"
},
"scripts": {
"test": "mocha --reporter spec --check-leaks --bail test/",
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/",
"test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/"
},
"version": "1.3.3"
}
node_modules/
test.js
npm-debug.log
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.initConfig({
jshint: {
all: [
'lib/**/*.js',
'./*.js',
'!./test.js'
]
}
});
};
\ No newline at end of file
# ajax-request — Simplified http request
[![NPM](https://nodei.co/npm/ajax-request.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/ajax-request/)
```js
var request = require('ajax-request');
```
## install
```
npm install ajax-request --save
```
### test
```
mocha
```
## API
### request(options, callback)
* {obejct|string} ``options`` required
If the options is string, it will send get request.
* {string} ``options.url`` required
* {string} ``options.method`` [options.method=GET]
The http request type
* {obejct} ``options.data``
if the request type is `GET`, it's appended to query string of the URL, or it's sended to remote of body.
* {object} ``options.headers``
An object containing request headers.
* {string} ``options.encoding``
Set response data encoding
* {boolean} ``options.isBuffer`` [options.isBuffer=false]
Parse response data to buffer
* {boolean} ``options.json`` [options.json=false]
Parse response data to json
* {function} ``callback`` required
```js
request('url', function(err, res, body) {});
request({
url: '',
method: 'GET',
data: {
query1: 'value1'
}
}, function(err, res, body) {
});
```
### .post(options, callback)
The API same as request
```js
request.post({
url: 'url',
data: {},
headers: {}
});
```
### .download(options, callback)
* {obejct} ``options`` required
* ``options.url`` {string} required
* ``options.ignore`` {boolean} [options.ignore=false]
Is the filepath ignore case.
* ``options.rootPath`` {string} [options.rootPath='']
The root of dest path
* ``options.destPath`` {string|function}
Custom the download path.
* {function} ``callback`` required
```js
request.download({
url: 'path/index.png',
rootPath: ''
}, function(err, res, body, destpath) {});
request.download({
url: 'path/index.png',
destPath: function(filename) {
return filename;
}
}, function(err, res, body, destpath) { });
```
### .base64(url, callback)
Deprecated, move to [base64](https://github.com/douzi8/base64-img#requestbase64url-callback)
\ No newline at end of file
/**
* @fileoverview Http request in node.js
* @author douzi <liaowei08@gmail.com>
*/
var http = require('http');
var util = require('utils-extend');
var url = require('url');
var path = require('path');
var querystring = require('querystring');
var file = require('file-system');
/**
* @description
* http request
* @param {object|string} [options]
* @param {function} [callback]
* @example
* request('url', function(err, res, body) { });
* request({url: '', headers: {}, method: 'POST'}, function(err, res, body) { });
*/
function request(options, callback) {
var opts = {
headers: {
'Content-Type': 'application/json'
},
method: 'GET',
encoding: 'utf8',
// If the callback body is buffer, it can hanlder document pipe simply
isBuffer: false,
json: false
};
if (util.isString(options)) {
opts.url = options;
} else {
util.extend(opts, options);
}
// Append request data
if (opts.data) {
if (opts.method === 'GET') {
opts.url += '?' + querystring.stringify(opts.data);
} else {
opts.data = JSON.stringify(opts.data);
opts.headers['Content-Length'] = opts.data.length;
}
}
// Extend request url object
util.extend(opts, util.pick(url.parse(opts.url), 'hostname', 'port', 'path', 'auth'));
delete opts.url;
var req = http.request(opts, function(res) {
var body = [];
var size = 0;
res.on('data', function(chunk) {
body.push(chunk);
size += chunk.length;
});
res.on('end', function() {
var result = '';
// Buffer
if (opts.isBuffer) {
result = Buffer.concat(body, size);
} else {
body.forEach(function(item) {
result += item.toString(opts.encoding);
});
if (opts.json) {
result = JSON.parse(result);
}
}
callback(null, res, result);
});
});
req.on('error', callback);
if (opts.method !== 'GET' && opts.data) {
req.write(opts.data);
}
req.end();
}
/**
* @description
* @example
* request.post('url', function() {});
* request.post({ url: 'url', data: { q1: 'v1' }}, function() {});
*/
request.post = function(options, callback) {
if (util.isString(options)) {
options = {
url: options
};
}
options.method = 'POST';
request(options, callback);
};
/**
* @description
* Download remote resurce to local file
* @example
* request.download({ url: 'path.png' }, function(err, res, body, filepath) {})
* request.download({
url: 'path.png',
rootPath: 'dest/path'
}, function(err, res, body, filepath) {
});
*/
request.download = function(options, callback) {
var opts = util.extend({
rootPath: '',
ignore: false
}, options);
request({
url: opts.url,
isBuffer: true
}, function(err, res, body) {
if (err) return callback(err);
if (res.statusCode !== 200) return callback(err, res, body);
var destPath;
var pathname = url.parse(options.url).pathname.replace(/^\//, '');
if (opts.destPath) {
if (util.isFunction(opts.destPath)) {
destPath = opts.destPath(path.basename(pathname));
} else {
destPath = opts.destPath;
}
} else {
destPath = path.join(
options.rootPath,
pathname
);
}
if (opts.ignore) {
destPath = destPath.toLowerCase();
}
file.writeFile(destPath, body, function(err) {
if (err) return callback(err);
callback(null, res, body, destPath);
});
});
};
module.exports = request;
\ No newline at end of file
{
"_args": [
[
{
"raw": "ajax-request",
"scope": null,
"escapedName": "ajax-request",
"name": "ajax-request",
"rawSpec": "",
"spec": "latest",
"type": "tag"
},
"C:\\Users\\Giuliano\\Desktop\\nasaproject\\project2"
]
],
"_from": "ajax-request@latest",
"_id": "ajax-request@1.2.1",
"_inCache": true,
"_location": "/ajax-request",
"_npmUser": {
"name": "douzi",
"email": "liaowei08@gmail.com"
},
"_npmVersion": "1.4.23",
"_phantomChildren": {},
"_requested": {
"raw": "ajax-request",
"scope": null,
"escapedName": "ajax-request",
"name": "ajax-request",
"rawSpec": "",
"spec": "latest",
"type": "tag"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/ajax-request/-/ajax-request-1.2.1.tgz",
"_shasum": "bca0b1cc922290659e2794fb395e64e7799c1d21",
"_shrinkwrap": null,
"_spec": "ajax-request",
"_where": "C:\\Users\\Giuliano\\Desktop\\nasaproject\\project2",
"author": {
"name": "douzi",
"email": "liaowei08@gmail.com"
},
"bugs": {
"url": "https://github.com/douzi8/ajax-request/issues"
},
"dependencies": {
"file-system": "^2.1.1",
"utils-extend": "^1.0.7"
},
"description": "Http request for nodejs, and it also support file download",
"devDependencies": {
"body-parser": "^1.10.2",
"express": "^4.11.1",
"grunt": "^0.4.5",
"grunt-contrib-jshint": "^0.10.0",
"serve-static": "^1.8.1"
},
"directories": {},
"dist": {
"shasum": "bca0b1cc922290659e2794fb395e64e7799c1d21",
"tarball": "https://registry.npmjs.org/ajax-request/-/ajax-request-1.2.1.tgz"
},
"gitHead": "05a7dcd659079755f440e8607c435281d254807f",
"homepage": "https://github.com/douzi8/ajax-request#readme",
"keywords": [
"request",
"http",
"ajax",
"http",
"request",
"http download",
"image",
"json",
"resource",
"download",
"file download",
"base64",
"image base64"
],
"license": "ISC",
"main": "index.js",
"maintainers": [
{
"name": "douzi",
"email": "liaowei08@gmail.com"
}
],
"name": "ajax-request",
"optionalDependencies": {},
"readme": "# ajax-request — Simplified http request\n[![NPM](https://nodei.co/npm/ajax-request.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/ajax-request/)\n```js\nvar request = require('ajax-request');\n```\n\n## install\n```\nnpm install ajax-request --save\n```\n\n### test\n```\nmocha\n```\n\n## API\n### request(options, callback)\n* {obejct|string} ``options`` required \n If the options is string, it will send get request.\n * {string} ``options.url`` required\n * {string} ``options.method`` [options.method=GET] \n The http request type\n * {obejct} ``options.data`` \n if the request type is `GET`, it's appended to query string of the URL, or it's sended to remote of body.\n * {object} ``options.headers`` \n An object containing request headers.\n * {string} ``options.encoding`` \n Set response data encoding\n * {boolean} ``options.isBuffer`` [options.isBuffer=false] \n Parse response data to buffer\n * {boolean} ``options.json`` [options.json=false] \n Parse response data to json\n* {function} ``callback`` required\n\n```js\nrequest('url', function(err, res, body) {});\n\nrequest({\n url: '',\n method: 'GET',\n data: {\n query1: 'value1'\n }\n}, function(err, res, body) {\n \n});\n```\n\n### .post(options, callback)\nThe API same as request\n```js\nrequest.post({\n url: 'url',\n data: {},\n headers: {}\n});\n```\n\n### .download(options, callback)\n* {obejct} ``options`` required\n * ``options.url`` {string} required\n * ``options.ignore`` {boolean} [options.ignore=false] \n Is the filepath ignore case. \n * ``options.rootPath`` {string} [options.rootPath=''] \n The root of dest path\n * ``options.destPath`` {string|function} \n Custom the download path.\n* {function} ``callback`` required\n\n```js\nrequest.download({\n url: 'path/index.png',\n rootPath: ''\n}, function(err, res, body, destpath) {});\n\nrequest.download({\n url: 'path/index.png',\n destPath: function(filename) {\n return filename;\n }\n}, function(err, res, body, destpath) { });\n\n```\n\n### .base64(url, callback)\nDeprecated, move to [base64](https://github.com/douzi8/base64-img#requestbase64url-callback)",
"readmeFilename": "README.md",
"repository": {
"type": "git",
"url": "git+https://github.com/douzi8/ajax-request.git"
},
"scripts": {
"test": "mocha"
},
"version": "1.2.1"
}
var assert = require('assert');
var app = require('./service/app');
var util = require('utils-extend');
var request = require('../index');
var fs = require('file-system');
var path = require('path');
var srcPath = path.join(__dirname, 'service/assets');
var rootPath = path.join(__dirname, 'download');
var server;
describe('Download request', function() {
// Start service
beforeEach(function(done){
server = app.listen(3100, function() {
done();
});
});
it('html', function(done) {
request.download({
url: 'http://127.0.0.1:3100/index.html',
rootPath: rootPath
}, function(err, res, body, dest) {
var c1 = fs.readFileSync(path.join(srcPath, 'index.html'));
var c2 = fs.readFileSync(path.join(rootPath, 'index.html'));
assert.equal(c1.length, c2.length);
assert.equal(c1.toString(), c2.toString());
done();
});
});
it('png', function(done) {
request.download({
url: 'http://127.0.0.1:3100/index.png',
rootPath: rootPath
}, function(err, res, body, dest) {
var c1 = fs.readFileSync(path.join(srcPath, 'index.png'));
var c2 = fs.readFileSync(path.join(rootPath, 'index.png'));
assert.equal(c1.length, c2.length);
assert.equal(c1.toString(), c2.toString());
done();
});
});
it('gif', function(done) {
request.download({
url: 'http://127.0.0.1:3100/index.gif',
rootPath: rootPath
}, function(err, res, body, dest) {
var c1 = fs.readFileSync(path.join(srcPath, 'index.gif'));
var c2 = fs.readFileSync(path.join(rootPath, 'index.gif'));
assert.equal(c1.length, c2.length);
assert.equal(c1.toString(), c2.toString());
done();
});
});
it('zip', function(done) {
request.download({
url: 'http://127.0.0.1:3100/index.zip',
rootPath: rootPath
}, function(err, res, body, dest) {
var c1 = fs.readFileSync(path.join(srcPath, 'index.zip'));
var c2 = fs.readFileSync(path.join(rootPath, 'index.zip'));
assert.equal(c1.length, c2.length);
assert.equal(c1.toString(), c2.toString());
done();
});
});
it('deep path', function(done) {
request.download({
url: 'http://127.0.0.1:3100/index.html',
rootPath: path.join(rootPath, '1/2')
}, function(err, res, body, dest) {
var c1 = fs.readFileSync(path.join(srcPath, 'index.html'));
var c2 = fs.readFileSync(path.join(path.join(rootPath, '1/2'), 'index.html'));
assert.equal(c1.length, c2.length);
assert.equal(c1.toString(), c2.toString());
done();
});
});
it('ignore', function(done) {
request.download({
url: 'http://127.0.0.1:3100/Capital/index.html',
ignore: true,
rootPath: rootPath
}, function(err, res, body, dest) {
var c1 = fs.readFileSync(path.join(srcPath, 'Capital/index.html'));
var c2 = fs.readFileSync(path.join(rootPath, 'capital/index.html'));
assert.equal(c1.length, c2.length);
assert.equal(c1.toString(), c2.toString());
done();
});
});
it('destPath string', function(done) {
var dest = path.join(rootPath, 'dest/index.html');
request.download({
url: 'http://127.0.0.1:3100/index.html',
destPath: dest
}, function(err, res, body, dest) {
var c1 = fs.readFileSync(path.join(srcPath, 'index.html'));
var c2 = fs.readFileSync(dest);
assert.equal(c1.length, c2.length);
assert.equal(c1.toString(), c2.toString());
done();
});
});
it('destPath function', function(done) {
var dest = path.join(rootPath, 'dest/index.html');
request.download({
url: 'http://127.0.0.1:3100/index.html',
destPath: function(filename) {
assert.equal(filename, 'index.html');
return dest;
}
}, function(err, res, body, dest) {
var c1 = fs.readFileSync(path.join(srcPath, 'index.html'));
var c2 = fs.readFileSync(dest);
assert.equal(c1.length, c2.length);
assert.equal(c1.toString(), c2.toString());
done();
});
});
afterEach(function(){
server.close();
fs.rmdirSync(rootPath);
});
});
\ No newline at end of file
var assert = require('assert');
var app = require('./service/app');
var util = require('utils-extend');
var request = require('../index');
var server;
describe('Request error', function() {
// Start service
beforeEach(function(done){
server = app.listen(3100, function() {
done();
});
});
it('404', function(done) {
request('http://127.0.0.1:3100/404', function(err, res, body) {
assert.equal(res.statusCode, 404);
done();
});
});
it('500', function(done) {
request('http://127.0.0.1:3100/500', function(err, res, body) {
assert.equal(res.statusCode, 500);
done();
});
});
afterEach(function(){
server.close();
});
});
\ No newline at end of file
var assert = require('assert');
var app = require('./service/app');
var util = require('utils-extend');
var request = require('../index');
var server;
describe('Http get', function() {
// Start service
beforeEach(function(done){
server = app.listen(3100, function() {
done();
});
});
it('Get html', function(done) {
request('http://127.0.0.1:3100', function(err, res, body) {
assert.equal(body, 'html');
done();
});
});
it('isString', function(done) {
request('http://127.0.0.1:3100/json', function(err, res, body) {
assert(util.isString(body));
done();
});
});
it('isJson', function(done) {
request({
url: 'http://127.0.0.1:3100/json',
json: true
}, function(err, res, body) {
assert(util.isObject(body));
done();
});
});
it('querystring', function(done) {
request({
url: 'http://127.0.0.1:3100/querystring',
json: true,
data: {
id: 1,
name: 'douzi'
}
}, function(err, res, body) {
assert(util.isObject(body));
assert.deepEqual(body, {
id: 1,
name: 'douzi'
});
done();
});
});
afterEach(function(){
server.close();
});
});
\ No newline at end of file
var assert = require('assert');
var app = require('./service/app');
var util = require('utils-extend');
var request = require('../index');
var server;
describe('Http post', function() {
// Start service
beforeEach(function(done){
server = app.listen(3100, function() {
done();
});
});
it('Request post', function(done) {
request({
url: 'http://127.0.0.1:3100/save',
method: 'POST',
data: {
id: 1
},
json: true
}, function(err, res, body) {
assert.deepEqual(body, { id: 1});
done();
});
});
it('Post method', function(done) {
request.post({
url: 'http://127.0.0.1:3100/save',
data: {
id: 1
},
json: true
}, function(err, res, body) {
assert.deepEqual(body, { id: 1});
done();
});
});
afterEach(function(){
server.close();
});
});
\ No newline at end of file
var express = require('express');
var app = express();
var path = require('path');
var serveStatic = require('serve-static');
var bodyParser = require('body-parser');
app.use(serveStatic(path.join(__dirname, 'assets'), { index: false }));
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.get('/', function (req, res) {
res.send('html');
});
app.get('/json', function(req, res) {
res.send({
id: 1
});
});
app.get('/querystring', function(req, res) {
res.send(req.query);
});
app.post('/save', function(req, res) {
res.send(req.body);
});
app.get('/500', function(req, res) {
res.status(500);
res.send('error');
});
module.exports = app;
\ No newline at end of file
chinese
中文
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment