Mitch Garnaat

Adding an initial S3 sample and code to register for event notification on an S3 bucket.

Showing 56 changed files with 5094 additions and 2 deletions
......@@ -170,7 +170,20 @@ class Kappa(object):
for log_event in response['events']:
print(log_event['message'])
def add_event_source(self):
def _get_function_arn(self):
name = self.config['lambda']['name']
arn = None
lambda_svc = self.session.create_client('lambda', self.region)
try:
response = lambda_svc.get_function_configuration(
FunctionName=name)
LOG.debug(response)
arn = response['FunctionARN']
except Exception:
LOG.debug('Unable to find ARN for function: %s' % name)
return arn
def _add_kinesis_event_source(self, event_source_arn):
lambda_svc = self.session.create_client('lambda', self.region)
try:
invoke_role = self.get_role_arn(
......@@ -178,12 +191,38 @@ class Kappa(object):
response = lambda_svc.add_event_source(
FunctionName=self.config['lambda']['name'],
Role=invoke_role,
EventSource=self.config['lambda']['event_source'],
EventSource=event_source_arn,
BatchSize=self.config['lambda'].get('batch_size', 100))
LOG.debug(response)
except Exception:
LOG.exception('Unable to add event source')
def _add_s3_event_source(self, event_source_arn):
s3_svc = self.session.create_client('s3', self.region)
bucket_name = event_source_arn.split(':')[-1]
invoke_role = self.get_role_arn(
self.config['cloudformation']['invoke_role'])
notification_spec = {
'CloudFunctionConfiguration': {
'Id': 'Kappa-%s-notification' % self.config['lambda']['name'],
'Events': [e for e in self.config['lambda']['s3_events']],
'CloudFunction': self._get_function_arn(),
'InvocationRole': invoke_role}}
response = s3_svc.put_bucket_notification(
Bucket=bucket_name,
NotificationConfiguration=notification_spec)
LOG.debug(response)
def add_event_source(self):
event_source_arn = self.config['lambda']['event_source']
_, _, svc, _ = event_source_arn.split(':', 3)
if svc == 'kinesis':
self._add_kinesis_event_source(event_source_arn)
elif svc == 's3':
self._add_s3_event_source(event_source_arn)
else:
raise ValueError('Unsupported event source: %s' % event_source_arn)
def deploy(self):
self.create_update_roles(
self.config['cloudformation']['stack_name'],
......
---
profile: personal
region: us-east-1
cloudformation:
template: roles.cf
stack_name: TestS3
exec_role: ExecRole
invoke_role: InvokeRole
lambda:
name: S3Sample
zipfile_name: S3Sample.zip
description: Testing S3 Lambda handler
path: examplefolder
handler: CreateThumbnail.handler
runtime: nodejs
memory_size: 128
timeout: 3
mode: event
test_data: input.json
event_source: arn:aws:s3:::garnaat_pub
s3_events:
- s3:ObjectCreated:*
\ No newline at end of file
// dependencies
var async = require('async');
var AWS = require('aws-sdk');
var gm = require('gm')
.subClass({ imageMagick: true }); // Enable ImageMagick integration.
var util = require('util');
// constants
var MAX_WIDTH = 100;
var MAX_HEIGHT = 100;
// get reference to S3 client
var s3 = new AWS.S3();
exports.handler = function(event, context) {
// Read options from the event.
console.log("Reading options from event:\n", util.inspect(event, {depth: 5}));
var srcBucket = event.Records[0].s3.bucket.name;
var srcKey = event.Records[0].s3.object.key;
var dstBucket = srcBucket + "resized";
var dstKey = "resized-" + srcKey;
// Sanity check: validate that source and destination are different buckets.
if (srcBucket == dstBucket) {
console.error("Destination bucket must not match source bucket.");
return;
}
// Infer the image type.
var typeMatch = srcKey.match(/\.([^.]*)$/);
if (!typeMatch) {
console.error('unable to infer image type for key ' + srcKey);
return;
}
var imageType = typeMatch[1];
if (imageType != "jpg" && imageType != "png") {
console.log('skipping non-image ' + srcKey);
return;
}
// Download the image from S3, transform, and upload to a different S3 bucket.
async.waterfall([
function download(next) {
// Download the image from S3 into a buffer.
s3.getObject({
Bucket: srcBucket,
Key: srcKey
},
next);
},
function tranform(response, next) {
gm(response.Body).size(function(err, size) {
// Infer the scaling factor to avoid stretching the image unnaturally.
var scalingFactor = Math.min(
MAX_WIDTH / size.width,
MAX_HEIGHT / size.height
);
var width = scalingFactor * size.width;
var height = scalingFactor * size.height;
// Transform the image buffer in memory.
this.resize(width, height)
.toBuffer(imageType, function(err, buffer) {
if (err) {
next(err);
} else {
next(null, response.ContentType, buffer);
}
});
});
},
function upload(contentType, data, next) {
// Stream the transformed image to a different S3 bucket.
s3.putObject({
Bucket: dstBucket,
Key: dstKey,
Body: data,
ContentType: contentType
},
next);
}
], function (err) {
if (err) {
console.error(
'Unable to resize ' + srcBucket + '/' + srcKey +
' and upload to ' + dstBucket + '/' + dstKey +
' due to an error: ' + err
);
} else {
console.log(
'Successfully resized ' + srcBucket + '/' + srcKey +
' and uploaded to ' + dstBucket + '/' + dstKey
);
}
context.done();
}
);
};
Copyright (c) 2010-2014 Caolan McMahon
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.
# Async.js
[![Build Status via Travis CI](https://travis-ci.org/caolan/async.svg?branch=master)](https://travis-ci.org/caolan/async)
Async is a utility module which provides straight-forward, powerful functions
for working with asynchronous JavaScript. Although originally designed for
use with [Node.js](http://nodejs.org), it can also be used directly in the
browser. Also supports [component](https://github.com/component/component).
Async provides around 20 functions that include the usual 'functional'
suspects (`map`, `reduce`, `filter`, `each`…) as well as some common patterns
for asynchronous control flow (`parallel`, `series`, `waterfall`…). All these
functions assume you follow the Node.js convention of providing a single
callback as the last argument of your `async` function.
## Quick Examples
```javascript
async.map(['file1','file2','file3'], fs.stat, function(err, results){
// results is now an array of stats for each file
});
async.filter(['file1','file2','file3'], fs.exists, function(results){
// results now equals an array of the existing files
});
async.parallel([
function(){ ... },
function(){ ... }
], callback);
async.series([
function(){ ... },
function(){ ... }
]);
```
There are many more functions available so take a look at the docs below for a
full list. This module aims to be comprehensive, so if you feel anything is
missing please create a GitHub issue for it.
## Common Pitfalls
### Binding a context to an iterator
This section is really about `bind`, not about `async`. If you are wondering how to
make `async` execute your iterators in a given context, or are confused as to why
a method of another library isn't working as an iterator, study this example:
```js
// Here is a simple object with an (unnecessarily roundabout) squaring method
var AsyncSquaringLibrary = {
squareExponent: 2,
square: function(number, callback){
var result = Math.pow(number, this.squareExponent);
setTimeout(function(){
callback(null, result);
}, 200);
}
};
async.map([1, 2, 3], AsyncSquaringLibrary.square, function(err, result){
// result is [NaN, NaN, NaN]
// This fails because the `this.squareExponent` expression in the square
// function is not evaluated in the context of AsyncSquaringLibrary, and is
// therefore undefined.
});
async.map([1, 2, 3], AsyncSquaringLibrary.square.bind(AsyncSquaringLibrary), function(err, result){
// result is [1, 4, 9]
// With the help of bind we can attach a context to the iterator before
// passing it to async. Now the square function will be executed in its
// 'home' AsyncSquaringLibrary context and the value of `this.squareExponent`
// will be as expected.
});
```
## Download
The source is available for download from
[GitHub](http://github.com/caolan/async).
Alternatively, you can install using Node Package Manager (`npm`):
npm install async
__Development:__ [async.js](https://github.com/caolan/async/raw/master/lib/async.js) - 29.6kb Uncompressed
## In the Browser
So far it's been tested in IE6, IE7, IE8, FF3.6 and Chrome 5.
Usage:
```html
<script type="text/javascript" src="async.js"></script>
<script type="text/javascript">
async.map(data, asyncProcess, function(err, results){
alert(results);
});
</script>
```
## Documentation
### Collections
* [`each`](#each)
* [`eachSeries`](#eachSeries)
* [`eachLimit`](#eachLimit)
* [`map`](#map)
* [`mapSeries`](#mapSeries)
* [`mapLimit`](#mapLimit)
* [`filter`](#filter)
* [`filterSeries`](#filterSeries)
* [`reject`](#reject)
* [`rejectSeries`](#rejectSeries)
* [`reduce`](#reduce)
* [`reduceRight`](#reduceRight)
* [`detect`](#detect)
* [`detectSeries`](#detectSeries)
* [`sortBy`](#sortBy)
* [`some`](#some)
* [`every`](#every)
* [`concat`](#concat)
* [`concatSeries`](#concatSeries)
### Control Flow
* [`series`](#seriestasks-callback)
* [`parallel`](#parallel)
* [`parallelLimit`](#parallellimittasks-limit-callback)
* [`whilst`](#whilst)
* [`doWhilst`](#doWhilst)
* [`until`](#until)
* [`doUntil`](#doUntil)
* [`forever`](#forever)
* [`waterfall`](#waterfall)
* [`compose`](#compose)
* [`seq`](#seq)
* [`applyEach`](#applyEach)
* [`applyEachSeries`](#applyEachSeries)
* [`queue`](#queue)
* [`priorityQueue`](#priorityQueue)
* [`cargo`](#cargo)
* [`auto`](#auto)
* [`retry`](#retry)
* [`iterator`](#iterator)
* [`apply`](#apply)
* [`nextTick`](#nextTick)
* [`times`](#times)
* [`timesSeries`](#timesSeries)
### Utils
* [`memoize`](#memoize)
* [`unmemoize`](#unmemoize)
* [`log`](#log)
* [`dir`](#dir)
* [`noConflict`](#noConflict)
## Collections
<a name="forEach" />
<a name="each" />
### each(arr, iterator, callback)
Applies the function `iterator` to each item in `arr`, in parallel.
The `iterator` is called with an item from the list, and a callback for when it
has finished. If the `iterator` passes an error to its `callback`, the main
`callback` (for the `each` function) is immediately called with the error.
Note, that since this function applies `iterator` to each item in parallel,
there is no guarantee that the iterator functions will complete in order.
__Arguments__
* `arr` - An array to iterate over.
* `iterator(item, callback)` - A function to apply to each item in `arr`.
The iterator is passed a `callback(err)` which must be called once it has
completed. If no error has occured, the `callback` should be run without
arguments or with an explicit `null` argument.
* `callback(err)` - A callback which is called when all `iterator` functions
have finished, or an error occurs.
__Examples__
```js
// assuming openFiles is an array of file names and saveFile is a function
// to save the modified contents of that file:
async.each(openFiles, saveFile, function(err){
// if any of the saves produced an error, err would equal that error
});
```
```js
// assuming openFiles is an array of file names
async.each(openFiles, function( file, callback) {
// Perform operation on file here.
console.log('Processing file ' + file);
if( file.length > 32 ) {
console.log('This file name is too long');
callback('File name too long');
} else {
// Do work to process file here
console.log('File processed');
callback();
}
}, function(err){
// if any of the file processing produced an error, err would equal that error
if( err ) {
// One of the iterations produced an error.
// All processing will now stop.
console.log('A file failed to process');
} else {
console.log('All files have been processed successfully');
}
});
```
---------------------------------------
<a name="forEachSeries" />
<a name="eachSeries" />
### eachSeries(arr, iterator, callback)
The same as [`each`](#each), only `iterator` is applied to each item in `arr` in
series. The next `iterator` is only called once the current one has completed.
This means the `iterator` functions will complete in order.
---------------------------------------
<a name="forEachLimit" />
<a name="eachLimit" />
### eachLimit(arr, limit, iterator, callback)
The same as [`each`](#each), only no more than `limit` `iterator`s will be simultaneously
running at any time.
Note that the items in `arr` are not processed in batches, so there is no guarantee that
the first `limit` `iterator` functions will complete before any others are started.
__Arguments__
* `arr` - An array to iterate over.
* `limit` - The maximum number of `iterator`s to run at any time.
* `iterator(item, callback)` - A function to apply to each item in `arr`.
The iterator is passed a `callback(err)` which must be called once it has
completed. If no error has occured, the callback should be run without
arguments or with an explicit `null` argument.
* `callback(err)` - A callback which is called when all `iterator` functions
have finished, or an error occurs.
__Example__
```js
// Assume documents is an array of JSON objects and requestApi is a
// function that interacts with a rate-limited REST api.
async.eachLimit(documents, 20, requestApi, function(err){
// if any of the saves produced an error, err would equal that error
});
```
---------------------------------------
<a name="map" />
### map(arr, iterator, callback)
Produces a new array of values by mapping each value in `arr` through
the `iterator` function. The `iterator` is called with an item from `arr` and a
callback for when it has finished processing. Each of these callback takes 2 arguments:
an `error`, and the transformed item from `arr`. If `iterator` passes an error to this
callback, the main `callback` (for the `map` function) is immediately called with the error.
Note, that since this function applies the `iterator` to each item in parallel,
there is no guarantee that the `iterator` functions will complete in order.
However, the results array will be in the same order as the original `arr`.
__Arguments__
* `arr` - An array to iterate over.
* `iterator(item, callback)` - A function to apply to each item in `arr`.
The iterator is passed a `callback(err, transformed)` which must be called once
it has completed with an error (which can be `null`) and a transformed item.
* `callback(err, results)` - A callback which is called when all `iterator`
functions have finished, or an error occurs. Results is an array of the
transformed items from the `arr`.
__Example__
```js
async.map(['file1','file2','file3'], fs.stat, function(err, results){
// results is now an array of stats for each file
});
```
---------------------------------------
<a name="mapSeries" />
### mapSeries(arr, iterator, callback)
The same as [`map`](#map), only the `iterator` is applied to each item in `arr` in
series. The next `iterator` is only called once the current one has completed.
The results array will be in the same order as the original.
---------------------------------------
<a name="mapLimit" />
### mapLimit(arr, limit, iterator, callback)
The same as [`map`](#map), only no more than `limit` `iterator`s will be simultaneously
running at any time.
Note that the items are not processed in batches, so there is no guarantee that
the first `limit` `iterator` functions will complete before any others are started.
__Arguments__
* `arr` - An array to iterate over.
* `limit` - The maximum number of `iterator`s to run at any time.
* `iterator(item, callback)` - A function to apply to each item in `arr`.
The iterator is passed a `callback(err, transformed)` which must be called once
it has completed with an error (which can be `null`) and a transformed item.
* `callback(err, results)` - A callback which is called when all `iterator`
calls have finished, or an error occurs. The result is an array of the
transformed items from the original `arr`.
__Example__
```js
async.mapLimit(['file1','file2','file3'], 1, fs.stat, function(err, results){
// results is now an array of stats for each file
});
```
---------------------------------------
<a name="select" />
<a name="filter" />
### filter(arr, iterator, callback)
__Alias:__ `select`
Returns a new array of all the values in `arr` which pass an async truth test.
_The callback for each `iterator` call only accepts a single argument of `true` or
`false`; it does not accept an error argument first!_ This is in-line with the
way node libraries work with truth tests like `fs.exists`. This operation is
performed in parallel, but the results array will be in the same order as the
original.
__Arguments__
* `arr` - An array to iterate over.
* `iterator(item, callback)` - A truth test to apply to each item in `arr`.
The `iterator` is passed a `callback(truthValue)`, which must be called with a
boolean argument once it has completed.
* `callback(results)` - A callback which is called after all the `iterator`
functions have finished.
__Example__
```js
async.filter(['file1','file2','file3'], fs.exists, function(results){
// results now equals an array of the existing files
});
```
---------------------------------------
<a name="selectSeries" />
<a name="filterSeries" />
### filterSeries(arr, iterator, callback)
__Alias:__ `selectSeries`
The same as [`filter`](#filter) only the `iterator` is applied to each item in `arr` in
series. The next `iterator` is only called once the current one has completed.
The results array will be in the same order as the original.
---------------------------------------
<a name="reject" />
### reject(arr, iterator, callback)
The opposite of [`filter`](#filter). Removes values that pass an `async` truth test.
---------------------------------------
<a name="rejectSeries" />
### rejectSeries(arr, iterator, callback)
The same as [`reject`](#reject), only the `iterator` is applied to each item in `arr`
in series.
---------------------------------------
<a name="reduce" />
### reduce(arr, memo, iterator, callback)
__Aliases:__ `inject`, `foldl`
Reduces `arr` into a single value using an async `iterator` to return
each successive step. `memo` is the initial state of the reduction.
This function only operates in series.
For performance reasons, it may make sense to split a call to this function into
a parallel map, and then use the normal `Array.prototype.reduce` on the results.
This function is for situations where each step in the reduction needs to be async;
if you can get the data before reducing it, then it's probably a good idea to do so.
__Arguments__
* `arr` - An array to iterate over.
* `memo` - The initial state of the reduction.
* `iterator(memo, item, callback)` - A function applied to each item in the
array to produce the next step in the reduction. The `iterator` is passed a
`callback(err, reduction)` which accepts an optional error as its first
argument, and the state of the reduction as the second. If an error is
passed to the callback, the reduction is stopped and the main `callback` is
immediately called with the error.
* `callback(err, result)` - A callback which is called after all the `iterator`
functions have finished. Result is the reduced value.
__Example__
```js
async.reduce([1,2,3], 0, function(memo, item, callback){
// pointless async:
process.nextTick(function(){
callback(null, memo + item)
});
}, function(err, result){
// result is now equal to the last value of memo, which is 6
});
```
---------------------------------------
<a name="reduceRight" />
### reduceRight(arr, memo, iterator, callback)
__Alias:__ `foldr`
Same as [`reduce`](#reduce), only operates on `arr` in reverse order.
---------------------------------------
<a name="detect" />
### detect(arr, iterator, callback)
Returns the first value in `arr` that passes an async truth test. The
`iterator` is applied in parallel, meaning the first iterator to return `true` will
fire the detect `callback` with that result. That means the result might not be
the first item in the original `arr` (in terms of order) that passes the test.
If order within the original `arr` is important, then look at [`detectSeries`](#detectSeries).
__Arguments__
* `arr` - An array to iterate over.
* `iterator(item, callback)` - A truth test to apply to each item in `arr`.
The iterator is passed a `callback(truthValue)` which must be called with a
boolean argument once it has completed.
* `callback(result)` - A callback which is called as soon as any iterator returns
`true`, or after all the `iterator` functions have finished. Result will be
the first item in the array that passes the truth test (iterator) or the
value `undefined` if none passed.
__Example__
```js
async.detect(['file1','file2','file3'], fs.exists, function(result){
// result now equals the first file in the list that exists
});
```
---------------------------------------
<a name="detectSeries" />
### detectSeries(arr, iterator, callback)
The same as [`detect`](#detect), only the `iterator` is applied to each item in `arr`
in series. This means the result is always the first in the original `arr` (in
terms of array order) that passes the truth test.
---------------------------------------
<a name="sortBy" />
### sortBy(arr, iterator, callback)
Sorts a list by the results of running each `arr` value through an async `iterator`.
__Arguments__
* `arr` - An array to iterate over.
* `iterator(item, callback)` - A function to apply to each item in `arr`.
The iterator is passed a `callback(err, sortValue)` which must be called once it
has completed with an error (which can be `null`) and a value to use as the sort
criteria.
* `callback(err, results)` - A callback which is called after all the `iterator`
functions have finished, or an error occurs. Results is the items from
the original `arr` sorted by the values returned by the `iterator` calls.
__Example__
```js
async.sortBy(['file1','file2','file3'], function(file, callback){
fs.stat(file, function(err, stats){
callback(err, stats.mtime);
});
}, function(err, results){
// results is now the original array of files sorted by
// modified date
});
```
__Sort Order__
By modifying the callback parameter the sorting order can be influenced:
```js
//ascending order
async.sortBy([1,9,3,5], function(x, callback){
callback(err, x);
}, function(err,result){
//result callback
} );
//descending order
async.sortBy([1,9,3,5], function(x, callback){
callback(err, x*-1); //<- x*-1 instead of x, turns the order around
}, function(err,result){
//result callback
} );
```
---------------------------------------
<a name="some" />
### some(arr, iterator, callback)
__Alias:__ `any`
Returns `true` if at least one element in the `arr` satisfies an async test.
_The callback for each iterator call only accepts a single argument of `true` or
`false`; it does not accept an error argument first!_ This is in-line with the
way node libraries work with truth tests like `fs.exists`. Once any iterator
call returns `true`, the main `callback` is immediately called.
__Arguments__
* `arr` - An array to iterate over.
* `iterator(item, callback)` - A truth test to apply to each item in the array
in parallel. The iterator is passed a callback(truthValue) which must be
called with a boolean argument once it has completed.
* `callback(result)` - A callback which is called as soon as any iterator returns
`true`, or after all the iterator functions have finished. Result will be
either `true` or `false` depending on the values of the async tests.
__Example__
```js
async.some(['file1','file2','file3'], fs.exists, function(result){
// if result is true then at least one of the files exists
});
```
---------------------------------------
<a name="every" />
### every(arr, iterator, callback)
__Alias:__ `all`
Returns `true` if every element in `arr` satisfies an async test.
_The callback for each `iterator` call only accepts a single argument of `true` or
`false`; it does not accept an error argument first!_ This is in-line with the
way node libraries work with truth tests like `fs.exists`.
__Arguments__
* `arr` - An array to iterate over.
* `iterator(item, callback)` - A truth test to apply to each item in the array
in parallel. The iterator is passed a callback(truthValue) which must be
called with a boolean argument once it has completed.
* `callback(result)` - A callback which is called after all the `iterator`
functions have finished. Result will be either `true` or `false` depending on
the values of the async tests.
__Example__
```js
async.every(['file1','file2','file3'], fs.exists, function(result){
// if result is true then every file exists
});
```
---------------------------------------
<a name="concat" />
### concat(arr, iterator, callback)
Applies `iterator` to each item in `arr`, concatenating the results. Returns the
concatenated list. The `iterator`s are called in parallel, and the results are
concatenated as they return. There is no guarantee that the results array will
be returned in the original order of `arr` passed to the `iterator` function.
__Arguments__
* `arr` - An array to iterate over.
* `iterator(item, callback)` - A function to apply to each item in `arr`.
The iterator is passed a `callback(err, results)` which must be called once it
has completed with an error (which can be `null`) and an array of results.
* `callback(err, results)` - A callback which is called after all the `iterator`
functions have finished, or an error occurs. Results is an array containing
the concatenated results of the `iterator` function.
__Example__
```js
async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){
// files is now a list of filenames that exist in the 3 directories
});
```
---------------------------------------
<a name="concatSeries" />
### concatSeries(arr, iterator, callback)
Same as [`concat`](#concat), but executes in series instead of parallel.
## Control Flow
<a name="series" />
### series(tasks, [callback])
Run the functions in the `tasks` array in series, each one running once the previous
function has completed. If any functions in the series pass an error to its
callback, no more functions are run, and `callback` is immediately called with the value of the error.
Otherwise, `callback` receives an array of results when `tasks` have completed.
It is also possible to use an object instead of an array. Each property will be
run as a function, and the results will be passed to the final `callback` as an object
instead of an array. This can be a more readable way of handling results from
[`series`](#series).
**Note** that while many implementations preserve the order of object properties, the
[ECMAScript Language Specifcation](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6)
explicitly states that
> The mechanics and order of enumerating the properties is not specified.
So if you rely on the order in which your series of functions are executed, and want
this to work on all platforms, consider using an array.
__Arguments__
* `tasks` - An array or object containing functions to run, each function is passed
a `callback(err, result)` it must call on completion with an error `err` (which can
be `null`) and an optional `result` value.
* `callback(err, results)` - An optional callback to run once all the functions
have completed. This function gets a results array (or object) containing all
the result arguments passed to the `task` callbacks.
__Example__
```js
async.series([
function(callback){
// do some stuff ...
callback(null, 'one');
},
function(callback){
// do some more stuff ...
callback(null, 'two');
}
],
// optional callback
function(err, results){
// results is now equal to ['one', 'two']
});
// an example using an object instead of an array
async.series({
one: function(callback){
setTimeout(function(){
callback(null, 1);
}, 200);
},
two: function(callback){
setTimeout(function(){
callback(null, 2);
}, 100);
}
},
function(err, results) {
// results is now equal to: {one: 1, two: 2}
});
```
---------------------------------------
<a name="parallel" />
### parallel(tasks, [callback])
Run the `tasks` array of functions in parallel, without waiting until the previous
function has completed. If any of the functions pass an error to its
callback, the main `callback` is immediately called with the value of the error.
Once the `tasks` have completed, the results are passed to the final `callback` as an
array.
It is also possible to use an object instead of an array. Each property will be
run as a function and the results will be passed to the final `callback` as an object
instead of an array. This can be a more readable way of handling results from
[`parallel`](#parallel).
__Arguments__
* `tasks` - An array or object containing functions to run. Each function is passed
a `callback(err, result)` which it must call on completion with an error `err`
(which can be `null`) and an optional `result` value.
* `callback(err, results)` - An optional callback to run once all the functions
have completed. This function gets a results array (or object) containing all
the result arguments passed to the task callbacks.
__Example__
```js
async.parallel([
function(callback){
setTimeout(function(){
callback(null, 'one');
}, 200);
},
function(callback){
setTimeout(function(){
callback(null, 'two');
}, 100);
}
],
// optional callback
function(err, results){
// the results array will equal ['one','two'] even though
// the second function had a shorter timeout.
});
// an example using an object instead of an array
async.parallel({
one: function(callback){
setTimeout(function(){
callback(null, 1);
}, 200);
},
two: function(callback){
setTimeout(function(){
callback(null, 2);
}, 100);
}
},
function(err, results) {
// results is now equals to: {one: 1, two: 2}
});
```
---------------------------------------
<a name="parallelLimit" />
### parallelLimit(tasks, limit, [callback])
The same as [`parallel`](#parallel), only `tasks` are executed in parallel
with a maximum of `limit` tasks executing at any time.
Note that the `tasks` are not executed in batches, so there is no guarantee that
the first `limit` tasks will complete before any others are started.
__Arguments__
* `tasks` - An array or object containing functions to run, each function is passed
a `callback(err, result)` it must call on completion with an error `err` (which can
be `null`) and an optional `result` value.
* `limit` - The maximum number of `tasks` to run at any time.
* `callback(err, results)` - An optional callback to run once all the functions
have completed. This function gets a results array (or object) containing all
the result arguments passed to the `task` callbacks.
---------------------------------------
<a name="whilst" />
### whilst(test, fn, callback)
Repeatedly call `fn`, while `test` returns `true`. Calls `callback` when stopped,
or an error occurs.
__Arguments__
* `test()` - synchronous truth test to perform before each execution of `fn`.
* `fn(callback)` - A function which is called each time `test` passes. The function is
passed a `callback(err)`, which must be called once it has completed with an
optional `err` argument.
* `callback(err)` - A callback which is called after the test fails and repeated
execution of `fn` has stopped.
__Example__
```js
var count = 0;
async.whilst(
function () { return count < 5; },
function (callback) {
count++;
setTimeout(callback, 1000);
},
function (err) {
// 5 seconds have passed
}
);
```
---------------------------------------
<a name="doWhilst" />
### doWhilst(fn, test, callback)
The post-check version of [`whilst`](#whilst). To reflect the difference in
the order of operations, the arguments `test` and `fn` are switched.
`doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.
---------------------------------------
<a name="until" />
### until(test, fn, callback)
Repeatedly call `fn` until `test` returns `true`. Calls `callback` when stopped,
or an error occurs.
The inverse of [`whilst`](#whilst).
---------------------------------------
<a name="doUntil" />
### doUntil(fn, test, callback)
Like [`doWhilst`](#doWhilst), except the `test` is inverted. Note the argument ordering differs from `until`.
---------------------------------------
<a name="forever" />
### forever(fn, errback)
Calls the asynchronous function `fn` with a callback parameter that allows it to
call itself again, in series, indefinitely.
If an error is passed to the callback then `errback` is called with the
error, and execution stops, otherwise it will never be called.
```js
async.forever(
function(next) {
// next is suitable for passing to things that need a callback(err [, whatever]);
// it will result in this function being called again.
},
function(err) {
// if next is called with a value in its first parameter, it will appear
// in here as 'err', and execution will stop.
}
);
```
---------------------------------------
<a name="waterfall" />
### waterfall(tasks, [callback])
Runs the `tasks` array of functions in series, each passing their results to the next in
the array. However, if any of the `tasks` pass an error to their own callback, the
next function is not executed, and the main `callback` is immediately called with
the error.
__Arguments__
* `tasks` - An array of functions to run, each function is passed a
`callback(err, result1, result2, ...)` it must call on completion. The first
argument is an error (which can be `null`) and any further arguments will be
passed as arguments in order to the next task.
* `callback(err, [results])` - An optional callback to run once all the functions
have completed. This will be passed the results of the last task's callback.
__Example__
```js
async.waterfall([
function(callback){
callback(null, 'one', 'two');
},
function(arg1, arg2, callback){
// arg1 now equals 'one' and arg2 now equals 'two'
callback(null, 'three');
},
function(arg1, callback){
// arg1 now equals 'three'
callback(null, 'done');
}
], function (err, result) {
// result now equals 'done'
});
```
---------------------------------------
<a name="compose" />
### compose(fn1, fn2...)
Creates a function which is a composition of the passed asynchronous
functions. Each function consumes the return value of the function that
follows. Composing functions `f()`, `g()`, and `h()` would produce the result of
`f(g(h()))`, only this version uses callbacks to obtain the return values.
Each function is executed with the `this` binding of the composed function.
__Arguments__
* `functions...` - the asynchronous functions to compose
__Example__
```js
function add1(n, callback) {
setTimeout(function () {
callback(null, n + 1);
}, 10);
}
function mul3(n, callback) {
setTimeout(function () {
callback(null, n * 3);
}, 10);
}
var add1mul3 = async.compose(mul3, add1);
add1mul3(4, function (err, result) {
// result now equals 15
});
```
---------------------------------------
<a name="seq" />
### seq(fn1, fn2...)
Version of the compose function that is more natural to read.
Each following function consumes the return value of the latter function.
Each function is executed with the `this` binding of the composed function.
__Arguments__
* functions... - the asynchronous functions to compose
__Example__
```js
// Requires lodash (or underscore), express3 and dresende's orm2.
// Part of an app, that fetches cats of the logged user.
// This example uses `seq` function to avoid overnesting and error
// handling clutter.
app.get('/cats', function(request, response) {
function handleError(err, data, callback) {
if (err) {
console.error(err);
response.json({ status: 'error', message: err.message });
}
else {
callback(data);
}
}
var User = request.models.User;
async.seq(
_.bind(User.get, User), // 'User.get' has signature (id, callback(err, data))
handleError,
function(user, fn) {
user.getCats(fn); // 'getCats' has signature (callback(err, data))
},
handleError,
function(cats) {
response.json({ status: 'ok', message: 'Cats found', data: cats });
}
)(req.session.user_id);
}
});
```
---------------------------------------
<a name="applyEach" />
### applyEach(fns, args..., callback)
Applies the provided arguments to each function in the array, calling
`callback` after all functions have completed. If you only provide the first
argument, then it will return a function which lets you pass in the
arguments as if it were a single function call.
__Arguments__
* `fns` - the asynchronous functions to all call with the same arguments
* `args...` - any number of separate arguments to pass to the function
* `callback` - the final argument should be the callback, called when all
functions have completed processing
__Example__
```js
async.applyEach([enableSearch, updateSchema], 'bucket', callback);
// partial application example:
async.each(
buckets,
async.applyEach([enableSearch, updateSchema]),
callback
);
```
---------------------------------------
<a name="applyEachSeries" />
### applyEachSeries(arr, iterator, callback)
The same as [`applyEach`](#applyEach) only the functions are applied in series.
---------------------------------------
<a name="queue" />
### queue(worker, concurrency)
Creates a `queue` object with the specified `concurrency`. Tasks added to the
`queue` are processed in parallel (up to the `concurrency` limit). If all
`worker`s are in progress, the task is queued until one becomes available.
Once a `worker` completes a `task`, that `task`'s callback is called.
__Arguments__
* `worker(task, callback)` - An asynchronous function for processing a queued
task, which must call its `callback(err)` argument when finished, with an
optional `error` as an argument.
* `concurrency` - An `integer` for determining how many `worker` functions should be
run in parallel.
__Queue objects__
The `queue` object returned by this function has the following properties and
methods:
* `length()` - a function returning the number of items waiting to be processed.
* `started` - a function returning whether or not any items have been pushed and processed by the queue
* `running()` - a function returning the number of items currently being processed.
* `idle()` - a function returning false if there are items waiting or being processed, or true if not.
* `concurrency` - an integer for determining how many `worker` functions should be
run in parallel. This property can be changed after a `queue` is created to
alter the concurrency on-the-fly.
* `push(task, [callback])` - add a new task to the `queue`. Calls `callback` once
the `worker` has finished processing the task. Instead of a single task, a `tasks` array
can be submitted. The respective callback is used for every task in the list.
* `unshift(task, [callback])` - add a new task to the front of the `queue`.
* `saturated` - a callback that is called when the `queue` length hits the `concurrency` limit,
and further tasks will be queued.
* `empty` - a callback that is called when the last item from the `queue` is given to a `worker`.
* `drain` - a callback that is called when the last item from the `queue` has returned from the `worker`.
* `paused` - a boolean for determining whether the queue is in a paused state
* `pause()` - a function that pauses the processing of tasks until `resume()` is called.
* `resume()` - a function that resumes the processing of queued tasks when the queue is paused.
* `kill()` - a function that empties remaining tasks from the queue forcing it to go idle.
__Example__
```js
// create a queue object with concurrency 2
var q = async.queue(function (task, callback) {
console.log('hello ' + task.name);
callback();
}, 2);
// assign a callback
q.drain = function() {
console.log('all items have been processed');
}
// add some items to the queue
q.push({name: 'foo'}, function (err) {
console.log('finished processing foo');
});
q.push({name: 'bar'}, function (err) {
console.log('finished processing bar');
});
// add some items to the queue (batch-wise)
q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) {
console.log('finished processing bar');
});
// add some items to the front of the queue
q.unshift({name: 'bar'}, function (err) {
console.log('finished processing bar');
});
```
---------------------------------------
<a name="priorityQueue" />
### priorityQueue(worker, concurrency)
The same as [`queue`](#queue) only tasks are assigned a priority and completed in ascending priority order. There are two differences between `queue` and `priorityQueue` objects:
* `push(task, priority, [callback])` - `priority` should be a number. If an array of
`tasks` is given, all tasks will be assigned the same priority.
* The `unshift` method was removed.
---------------------------------------
<a name="cargo" />
### cargo(worker, [payload])
Creates a `cargo` object with the specified payload. Tasks added to the
cargo will be processed altogether (up to the `payload` limit). If the
`worker` is in progress, the task is queued until it becomes available. Once
the `worker` has completed some tasks, each callback of those tasks is called.
Check out [this animation](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) for how `cargo` and `queue` work.
While [queue](#queue) passes only one task to one of a group of workers
at a time, cargo passes an array of tasks to a single worker, repeating
when the worker is finished.
__Arguments__
* `worker(tasks, callback)` - An asynchronous function for processing an array of
queued tasks, which must call its `callback(err)` argument when finished, with
an optional `err` argument.
* `payload` - An optional `integer` for determining how many tasks should be
processed per round; if omitted, the default is unlimited.
__Cargo objects__
The `cargo` object returned by this function has the following properties and
methods:
* `length()` - A function returning the number of items waiting to be processed.
* `payload` - An `integer` for determining how many tasks should be
process per round. This property can be changed after a `cargo` is created to
alter the payload on-the-fly.
* `push(task, [callback])` - Adds `task` to the `queue`. The callback is called
once the `worker` has finished processing the task. Instead of a single task, an array of `tasks`
can be submitted. The respective callback is used for every task in the list.
* `saturated` - A callback that is called when the `queue.length()` hits the concurrency and further tasks will be queued.
* `empty` - A callback that is called when the last item from the `queue` is given to a `worker`.
* `drain` - A callback that is called when the last item from the `queue` has returned from the `worker`.
__Example__
```js
// create a cargo object with payload 2
var cargo = async.cargo(function (tasks, callback) {
for(var i=0; i<tasks.length; i++){
console.log('hello ' + tasks[i].name);
}
callback();
}, 2);
// add some items
cargo.push({name: 'foo'}, function (err) {
console.log('finished processing foo');
});
cargo.push({name: 'bar'}, function (err) {
console.log('finished processing bar');
});
cargo.push({name: 'baz'}, function (err) {
console.log('finished processing baz');
});
```
---------------------------------------
<a name="auto" />
### auto(tasks, [callback])
Determines the best order for running the functions in `tasks`, based on their
requirements. Each function can optionally depend on other functions being completed
first, and each function is run as soon as its requirements are satisfied.
If any of the functions pass an error to their callback, it will not
complete (so any other functions depending on it will not run), and the main
`callback` is immediately called with the error. Functions also receive an
object containing the results of functions which have completed so far.
Note, all functions are called with a `results` object as a second argument,
so it is unsafe to pass functions in the `tasks` object which cannot handle the
extra argument.
For example, this snippet of code:
```js
async.auto({
readData: async.apply(fs.readFile, 'data.txt', 'utf-8')
}, callback);
```
will have the effect of calling `readFile` with the results object as the last
argument, which will fail:
```js
fs.readFile('data.txt', 'utf-8', cb, {});
```
Instead, wrap the call to `readFile` in a function which does not forward the
`results` object:
```js
async.auto({
readData: function(cb, results){
fs.readFile('data.txt', 'utf-8', cb);
}
}, callback);
```
__Arguments__
* `tasks` - An object. Each of its properties is either a function or an array of
requirements, with the function itself the last item in the array. The object's key
of a property serves as the name of the task defined by that property,
i.e. can be used when specifying requirements for other tasks.
The function receives two arguments: (1) a `callback(err, result)` which must be
called when finished, passing an `error` (which can be `null`) and the result of
the function's execution, and (2) a `results` object, containing the results of
the previously executed functions.
* `callback(err, results)` - An optional callback which is called when all the
tasks have been completed. It receives the `err` argument if any `tasks`
pass an error to their callback. Results are always returned; however, if
an error occurs, no further `tasks` will be performed, and the results
object will only contain partial results.
__Example__
```js
async.auto({
get_data: function(callback){
console.log('in get_data');
// async code to get some data
callback(null, 'data', 'converted to array');
},
make_folder: function(callback){
console.log('in make_folder');
// async code to create a directory to store a file in
// this is run at the same time as getting the data
callback(null, 'folder');
},
write_file: ['get_data', 'make_folder', function(callback, results){
console.log('in write_file', JSON.stringify(results));
// once there is some data and the directory exists,
// write the data to a file in the directory
callback(null, 'filename');
}],
email_link: ['write_file', function(callback, results){
console.log('in email_link', JSON.stringify(results));
// once the file is written let's email a link to it...
// results.write_file contains the filename returned by write_file.
callback(null, {'file':results.write_file, 'email':'user@example.com'});
}]
}, function(err, results) {
console.log('err = ', err);
console.log('results = ', results);
});
```
This is a fairly trivial example, but to do this using the basic parallel and
series functions would look like this:
```js
async.parallel([
function(callback){
console.log('in get_data');
// async code to get some data
callback(null, 'data', 'converted to array');
},
function(callback){
console.log('in make_folder');
// async code to create a directory to store a file in
// this is run at the same time as getting the data
callback(null, 'folder');
}
],
function(err, results){
async.series([
function(callback){
console.log('in write_file', JSON.stringify(results));
// once there is some data and the directory exists,
// write the data to a file in the directory
results.push('filename');
callback(null);
},
function(callback){
console.log('in email_link', JSON.stringify(results));
// once the file is written let's email a link to it...
callback(null, {'file':results.pop(), 'email':'user@example.com'});
}
]);
});
```
For a complicated series of `async` tasks, using the [`auto`](#auto) function makes adding
new tasks much easier (and the code more readable).
---------------------------------------
<a name="retry" />
### retry([times = 5], task, [callback])
Attempts to get a successful response from `task` no more than `times` times before
returning an error. If the task is successful, the `callback` will be passed the result
of the successfull task. If all attemps fail, the callback will be passed the error and
result (if any) of the final attempt.
__Arguments__
* `times` - An integer indicating how many times to attempt the `task` before giving up. Defaults to 5.
* `task(callback, results)` - A function which receives two arguments: (1) a `callback(err, result)`
which must be called when finished, passing `err` (which can be `null`) and the `result` of
the function's execution, and (2) a `results` object, containing the results of
the previously executed functions (if nested inside another control flow).
* `callback(err, results)` - An optional callback which is called when the
task has succeeded, or after the final failed attempt. It receives the `err` and `result` arguments of the last attempt at completing the `task`.
The [`retry`](#retry) function can be used as a stand-alone control flow by passing a
callback, as shown below:
```js
async.retry(3, apiMethod, function(err, result) {
// do something with the result
});
```
It can also be embeded within other control flow functions to retry individual methods
that are not as reliable, like this:
```js
async.auto({
users: api.getUsers.bind(api),
payments: async.retry(3, api.getPayments.bind(api))
}, function(err, results) {
// do something with the results
});
```
---------------------------------------
<a name="iterator" />
### iterator(tasks)
Creates an iterator function which calls the next function in the `tasks` array,
returning a continuation to call the next one after that. It's also possible to
“peek” at the next iterator with `iterator.next()`.
This function is used internally by the `async` module, but can be useful when
you want to manually control the flow of functions in series.
__Arguments__
* `tasks` - An array of functions to run.
__Example__
```js
var iterator = async.iterator([
function(){ sys.p('one'); },
function(){ sys.p('two'); },
function(){ sys.p('three'); }
]);
node> var iterator2 = iterator();
'one'
node> var iterator3 = iterator2();
'two'
node> iterator3();
'three'
node> var nextfn = iterator2.next();
node> nextfn();
'three'
```
---------------------------------------
<a name="apply" />
### apply(function, arguments..)
Creates a continuation function with some arguments already applied.
Useful as a shorthand when combined with other control flow functions. Any arguments
passed to the returned function are added to the arguments originally passed
to apply.
__Arguments__
* `function` - The function you want to eventually apply all arguments to.
* `arguments...` - Any number of arguments to automatically apply when the
continuation is called.
__Example__
```js
// using apply
async.parallel([
async.apply(fs.writeFile, 'testfile1', 'test1'),
async.apply(fs.writeFile, 'testfile2', 'test2'),
]);
// the same process without using apply
async.parallel([
function(callback){
fs.writeFile('testfile1', 'test1', callback);
},
function(callback){
fs.writeFile('testfile2', 'test2', callback);
}
]);
```
It's possible to pass any number of additional arguments when calling the
continuation:
```js
node> var fn = async.apply(sys.puts, 'one');
node> fn('two', 'three');
one
two
three
```
---------------------------------------
<a name="nextTick" />
### nextTick(callback)
Calls `callback` on a later loop around the event loop. In Node.js this just
calls `process.nextTick`; in the browser it falls back to `setImmediate(callback)`
if available, otherwise `setTimeout(callback, 0)`, which means other higher priority
events may precede the execution of `callback`.
This is used internally for browser-compatibility purposes.
__Arguments__
* `callback` - The function to call on a later loop around the event loop.
__Example__
```js
var call_order = [];
async.nextTick(function(){
call_order.push('two');
// call_order now equals ['one','two']
});
call_order.push('one')
```
<a name="times" />
### times(n, callback)
Calls the `callback` function `n` times, and accumulates results in the same manner
you would use with [`map`](#map).
__Arguments__
* `n` - The number of times to run the function.
* `callback` - The function to call `n` times.
__Example__
```js
// Pretend this is some complicated async factory
var createUser = function(id, callback) {
callback(null, {
id: 'user' + id
})
}
// generate 5 users
async.times(5, function(n, next){
createUser(n, function(err, user) {
next(err, user)
})
}, function(err, users) {
// we should now have 5 users
});
```
<a name="timesSeries" />
### timesSeries(n, callback)
The same as [`times`](#times), only the iterator is applied to each item in `arr` in
series. The next `iterator` is only called once the current one has completed.
The results array will be in the same order as the original.
## Utils
<a name="memoize" />
### memoize(fn, [hasher])
Caches the results of an `async` function. When creating a hash to store function
results against, the callback is omitted from the hash and an optional hash
function can be used.
The cache of results is exposed as the `memo` property of the function returned
by `memoize`.
__Arguments__
* `fn` - The function to proxy and cache results from.
* `hasher` - Tn optional function for generating a custom hash for storing
results. It has all the arguments applied to it apart from the callback, and
must be synchronous.
__Example__
```js
var slow_fn = function (name, callback) {
// do something
callback(null, result);
};
var fn = async.memoize(slow_fn);
// fn can now be used as if it were slow_fn
fn('some name', function () {
// callback
});
```
<a name="unmemoize" />
### unmemoize(fn)
Undoes a [`memoize`](#memoize)d function, reverting it to the original, unmemoized
form. Handy for testing.
__Arguments__
* `fn` - the memoized function
<a name="log" />
### log(function, arguments)
Logs the result of an `async` function to the `console`. Only works in Node.js or
in browsers that support `console.log` and `console.error` (such as FF and Chrome).
If multiple arguments are returned from the async function, `console.log` is
called on each argument in order.
__Arguments__
* `function` - The function you want to eventually apply all arguments to.
* `arguments...` - Any number of arguments to apply to the function.
__Example__
```js
var hello = function(name, callback){
setTimeout(function(){
callback(null, 'hello ' + name);
}, 1000);
};
```
```js
node> async.log(hello, 'world');
'hello world'
```
---------------------------------------
<a name="dir" />
### dir(function, arguments)
Logs the result of an `async` function to the `console` using `console.dir` to
display the properties of the resulting object. Only works in Node.js or
in browsers that support `console.dir` and `console.error` (such as FF and Chrome).
If multiple arguments are returned from the async function, `console.dir` is
called on each argument in order.
__Arguments__
* `function` - The function you want to eventually apply all arguments to.
* `arguments...` - Any number of arguments to apply to the function.
__Example__
```js
var hello = function(name, callback){
setTimeout(function(){
callback(null, {hello: name});
}, 1000);
};
```
```js
node> async.dir(hello, 'world');
{hello: 'world'}
```
---------------------------------------
<a name="noConflict" />
### noConflict()
Changes the value of `async` back to its original value, returning a reference to the
`async` object.
{
"name": "async",
"repo": "caolan/async",
"description": "Higher-order functions and common patterns for asynchronous code",
"version": "0.1.23",
"keywords": [],
"dependencies": {},
"development": {},
"main": "lib/async.js",
"scripts": [ "lib/async.js" ]
}
{
"name": "async",
"description": "Higher-order functions and common patterns for asynchronous code",
"main": "./lib/async",
"author": {
"name": "Caolan McMahon"
},
"version": "0.9.0",
"repository": {
"type": "git",
"url": "https://github.com/caolan/async.git"
},
"bugs": {
"url": "https://github.com/caolan/async/issues"
},
"licenses": [
{
"type": "MIT",
"url": "https://github.com/caolan/async/raw/master/LICENSE"
}
],
"devDependencies": {
"nodeunit": ">0.0.0",
"uglify-js": "1.2.x",
"nodelint": ">0.0.0"
},
"jam": {
"main": "lib/async.js",
"include": [
"lib/async.js",
"README.md",
"LICENSE"
]
},
"scripts": {
"test": "nodeunit test/test-async.js"
},
"homepage": "https://github.com/caolan/async",
"_id": "async@0.9.0",
"dist": {
"shasum": "ac3613b1da9bed1b47510bb4651b8931e47146c7",
"tarball": "http://registry.npmjs.org/async/-/async-0.9.0.tgz"
},
"_from": "async@",
"_npmVersion": "1.4.3",
"_npmUser": {
"name": "caolan",
"email": "caolan.mcmahon@gmail.com"
},
"maintainers": [
{
"name": "caolan",
"email": "caolan@caolanmcmahon.com"
}
],
"directories": {},
"_shasum": "ac3613b1da9bed1b47510bb4651b8931e47146c7",
"_resolved": "https://registry.npmjs.org/async/-/async-0.9.0.tgz",
"readme": "ERROR: No README data found!"
}
before_install:
- sudo apt-get update
- sudo apt-get install imagemagick graphicsmagick
language: node_js
node_js:
- "0.8"
- "0.10"
1.17.0 / 2014-10-28
==================
* changed: extended compare callback also returns the file names #297 [mastix](https://github.com/mastix)
* changed: pass spawn crash to callback #306 [medikoo](https://github.com/medikoo)
* changed: geometry supports arbitary string as first argument #330 [jdiez17](https://github.com/jdiez17)
* added: support for repage+ option #275 [desigens](https://github.com/desigens)
* added: added the dissolve command #300 [microadm](https://github.com/microadam)
* added: composite method #332 [jdiez17](https://github.com/jdiez17)
* fixed: cannot set tolerance to 0 #302 [rwky](https://github.com/rwky)
* fixed: handle empty buffers #330 [alcidesv](https://github.com/alcidesv)
1.16.0 / 2014-05-09
==================
* fixed; dropped "+" when 0 passed as vertical roll amt #267 [dwtkns](https://github.com/dwtkns)
* added; highlight-style support #272 [fdecampredon](https://github.com/fdecampredon)
1.15.0 / 2014-05-03
===================
* changed; gm.compare logic to always run the mse comparison as expected #258 [Vokkim](https://github.com/Vokkim)
* added; `tolerance` to gm.compare options object #258 [Vokkim](https://github.com/Vokkim)
* added; option to set ImageMagick application path explicitly #250 (akreitals)
* fixed; gm.compare: support values like 9.51582e-05 #260 [normanrz](https://github.com/normanrz)
* README: add call for maintainers
1.14.2 / 2013-12-24
===================
* fixed; background is now a setting #246 (PEM--)
1.14.1 / 2013-12-09
===================
* fixed; identify -verbose colon behavior #240 ludow
1.14.0 / 2013-12-04
===================
* added; compare method for imagemagick (longlho)
1.13.3 / 2013-10-22
===================
* fixed; escape diffOptions.file in compare (dwabyick)
1.13.2 / 2013-10-18
===================
* fixed; density is a setting not an operator
1.13.1 / 2013-09-15
===================
* added; boolean for % crop
1.13.0 / 2013-09-07
===================
* added; morph more than two images (overra)
1.12.2 / 2013-08-29
===================
* fixed; fallback to through in node 0.8
1.12.1 / 2013-08-29 (unpublished)
===================
* refactor; replace through with stream.PassThrough
1.12.0 / 2013-08-27
===================
* added; diff image output file (chenglou)
1.11.1 / 2013-08-17
===================
* added; proto.selectFrame(#)
* fixed; getters should not ignore frame selection
1.11.0 / 2013-07-23
===================
* added; optional formatting string for gm().identify(format, callback) (tornillo)
* removed; error messages when gm/im binary is not installed
1.10.0 / 2013-06-27
===================
* refactor; use native `-auto-orient` for imagemagick
1.9.2 / 2013-06-12
==================
* refactor; move `streamToBuffer` to a separate module
* fixed; .stream(format) without a callback
1.9.1 / 2013-05-07
==================
* fixed; gm().resize(width) always only resizes width
* fixed; gm('img.gif').format() returns the format of the first frame
1.9.0 / 2013-04-21
==================
* added; node v0.10 support
* removed; node < v0.8 support - `Buffer.concat()`
* tests; all tests now run on Travis
* added; gm().stream() returns a stream when no callback is present
* added; gm().toBuffer(callback)
* fixed; gm().size() only returns the size of the first frame of a GIF
1.8.2 / 2013-03-07
==================
* include source path in identify data #126 [soupdiver](https://github.com/soupdiver)
1.8.1 / 2012-12-21
==================
* Avoid losing already set arguments on identify #105 #113 #109 [JNissi](https://github.com/JNissi)
* tests; add autoOrient + thumb() test
* tests; add test case for #113
* tests; added test for #109
* tests; add resize on buffer test
1.8.0 / 2012-12-14
==================
* added; geometry support to scale() #98
* removed; incorrect/broken dissolve() method (never worked)
* fixed; handle child_proc error when using Buffer input #109
* fixed; use of Buffers with identify() #109
* fixed; no longer include -size arg with resize() #98
* fixed; remove -size arg from extent() #103
* fixed; magnify support
* fixed; autoOrient to work with all types of exif orientations [dambalah](https://github.com/dambalah) #108
* tests; npm test runs unit only (now compatible with travis)
* tests; fix magnify test on imagemagick
* tests; added for cmd line args
1.7.0 / 2012-12-06
==================
* added; gm.compare support
* added; passing Buffers directly [danmilon](https://github.com/danmilon)
1.6.1 / 2012-11-13
==================
* fixed regression; only pass additional params on error #96
1.6.0 / 2012-11-10
==================
* changed; rename internal buffer to _buffer #88 [kof](https://github.com/kof)
* changed; optimized identify getters (format, depth, size, color, filesize). #83 please read this for details: https://github.com/aheckmann/gm/commit/8fcf3f8f84a02cc2001da874cbebb89bf7084409
* added; visionmedia/debug support
* added; `gm convert -thumbnail` support. _differs from thumb()._ [danmilon](https://github.com/danmilon)
* fixed; -rotate 0 support #90
* fixed; multi-execution of same gm instance arguments corruption
* fixed; gracefully handle parser errors #94 [eldilibra](https://github.com/eldilibra)
1.5.1 / 2012-10-02
==================
* fixed; passing multiple paths to append() #77
1.5.0 / 2012-09-15
==================
* fixed; callback scope
* fixed; append() usage #77
1.4.2 / 2012-08-17
==================
* fixed; identify parsing for ImageMagick exif data (#58)
* fixed; when in imageMagick mode, complain about missing imageMagick [bcherry](https://github.com/bcherry) (#73)
* added; tests
1.4.1 / 2012-07-31
==================
* fixed; scenes() args
* fixed; accept the left-to-right arg of append()
* added; _subCommand
## v1.4 - 07/28/2012
* added; adjoin() [Math-]
* added; affine() [Math-]
* added; append() [Math-]
* added; authenticate() [Math-]
* added; average() [Math-]
* added; backdrop() [Math-]
* added; blackThreshold() [Math-]
* added; bluePrimary() [Math-]
* added; border() [Math-]
* added; borderColor() [Math-]
* added; box() [Math-]
* added; channel() [Math-]
* added; clip() [Math-]
* added; coalesce() [Math-]
* added; colorMap() [Math-]
* added; compose() [Math-]
* added; compress() [Math-]
* added; convolve() [Math-]
* added; createDirectories() [Math-]
* added; deconstruct() [Math-]
* added; delay() [Math-]
* added; define() [Math-]
* added; displace() [Math-]
* added; display() [Math-]
* added; dispose() [Math-]
* added; disolve() [Math-]
* added; encoding() [Math-]
* added; endian() [Math-]
* added; file() [Math-]
* added; flatten() [Math-]
* added; foreground() [Math-]
* added; frame() [Math-]
* added; fuzz() [Math-]
* added; gaussian() [Math-]
* added; geometry() [Math-]
* added; greenPrimary() [Math-]
* added; highlightColor() [Math-]
* added; highlightStyle() [Math-]
* added; iconGeometry() [Math-]
* added; intent() [Math-]
* added; lat() [Math-]
* added; level() [Math-]
* added; list() [Math-]
* added; log() [Math-]
* added; map() [Math-]
* added; matte() [Math-]
* added; matteColor() [Math-]
* added; mask() [Math-]
* added; maximumError() [Math-]
* added; mode() [Math-]
* added; monitor() [Math-]
* added; mosaic() [Math-]
* added; motionBlur() [Math-]
* added; name() [Math-]
* added; noop() [Math-]
* added; normalize() [Math-]
* added; opaque() [Math-]
* added; operator() [Math-]
* added; orderedDither() [Math-]
* added; outputDirectory() [Math-]
* added; page() [Math-]
* added; pause() [Math-]
* added; pen() [Math-]
* added; ping() [Math-]
* added; pointSize() [Math-]
* added; preview() [Math-]
* added; process() [Math-]
* added; profile() [Math-]
* added; progress() [Math-]
* added; rawSize() [Math-]
* added; randomThreshold() [Math-]
* added; recolor() [Math-]
* added; redPrimary() [Math-]
* added; remote() [Math-]
* added; render() [Math-]
* added; repage() [Math-]
* added; sample() [Math-]
* added; samplingFactor() [Math-]
* added; scene() [Math-]
* added; scenes() [Math-]
* added; screen() [Math-]
* added; segment() [Math-]
* added; set() [Math-]
* added; shade() [Math-]
* added; shadow() [Math-]
* added; sharedMemory() [Math-]
* added; shave() [Math-]
* added; shear() [Math-]
* added; silent() [Math-]
* added; snaps() [Math-]
* added; stagano() [Math-]
* added; stereo() [Math-]
* added; textFont() [Math-]
* added; texture() [Math-]
* added; threshold() [Math-]
* added; tile() [Math-]
* added; transform() [Math-]
* added; transparent() [Math-]
* added; treeDepth() [Math-]
* added; update() [Math-]
* added; units() [Math-]
* added; unsharp() [Math-]
* added; usePixmap() [Math-]
* added; view() [Math-]
* added; virtualPixel() [Math-]
* added; visual() [Math-]
* added; watermark() [Math-]
* added; wave() [Math-]
* added; whitePoint() [Math-]
* added; whiteThreshold() [Math-]
* added; window() [Math-]
* added; windowGroup() [Math-]
## v1.3.2 - 06/22/2012
* added; node >= 0.7/0.8 compat
## v1.3.1 - 06/06/2012
* fixed; thumb() alignment and cropping [thomaschaaf]
* added; hint when graphicsmagick is not installed (#62)
* fixed; minify() (#59)
## v1.3.0 - 04/11/2012
* added; flatten support [jwarchol]
* added; background support [jwarchol]
* fixed; identify parser error [chriso]
## v1.2.0 - 03/30/2012
* added; extent and gravity support [jwarchol]
## v1.1.0 - 03/15/2012
* added; filter() support [travisbeck]
* added; density() [travisbeck]
* fixed; permit either width or height in resize [dambalah]
* updated; docs
## v1.0.5 - 02/15/2012
* added; strip() support [Math-]
* added; interlace() support [Math-]
* added; setFormat() support [Math-]
* fixed; regexps for image types [Math-]
## v1.0.4 - 02/09/2012
* expose utils
## v1.0.3 - 01/27/2012
* removed; console.log
## v1.0.2 - 01/24/2012
* added; debugging info on parser errors
* fixed; exports.version
## v1.0.1 - 01/12/2012
* fixed; use of reserved keyword `super` for node v0.5+
## v1.0.0 - 01/12/2012
* added; autoOrient support [kainosnoema] (#21)
* added; orientation support [kainosnoema] (#21)
* fixed; identify parser now properly JSON formats all data output by `gm identify` such as IPTC, GPS, Make, etc (#20)
* added; support for running as imagemagick (#23, #29)
* added; subclassing support; useful for setting default constructor options like one constructor for ImageMagick, the other for GM
* added; more tests
* changed; remove redundant `orientation`, `resolution`, and `filesize` from `this.data` in `indentify()`. Use their uppercase equivalents.
## v0.6.0 - 12/14/2011
* added; stream support [kainosnoema] (#22)
## v0.5.0 - 07/07/2011
* added; gm#trim() support [lepokle]
* added; gm#inputIs() support
* fixed; 'geometry does not contain image' error: gh-17
## v0.4.3 - 05/17/2011
* added; bunch of tests
* fixed; polygon, polyline, bezier drawing bug
## v0.4.2 - 05/10/2011
* added; resize options support
## v0.4.1 - 04/28/2011
* shell args are now escaped (thanks @visionmedia)
* added; gm.in()
* added; gm.out()
* various refactoring
## v0.4.0 - 9/21/2010
* removed deprecated `new` method
* added drawing docs
## v0.3.2 - 9/06/2010
* new images are now created using same gm() constructor
## v0.3.1 - 9/06/2010
* can now create images from scratch
* add type method
## v0.3.0 - 8/26/2010
* add drawing api
## v0.2.2 - 8/22/2010
* add quality option to thumb()
* add teropa to contributors
* added support for colorspace()
## v0.2.1 - 7/31/2010
* fixed naming conflict. depth() manipulation method renamed bitdepth()
* added better docs
## v0.2.0 - 7/29/2010
new methods
- swirl
- spread
- solarize
- sharpen
- roll
- sepia
- region
- raise
- lower
- paint
- noise
- negative
- morph
- median
- antialias
- limit
- label
- implode
- gamma
- enhance
- equalize
- emboss
- edge
- dither
- monochrome
- despeckle
- depth
- cycle
- contrast
- comment
- colors
added more default args to several methods
added more examples
## v0.1.2 - 7/28/2010
* refactor project into separate modules
## v0.1.1 - 7/27/2010
* add modulate method
* add colorize method
* add charcoal method
* add chop method
* bug fix in write without a callback
## v0.1.0 - 6/27/2010
* no longer supporting mogrify
* add image data getter methods
* size
* format
* color
* res
* depth
* filesize
* identify
* add new convert methods
* scale
* resample
* rotate
* flip
* flop
* crop
* magnify
* minify
* quality
* blur
* thumb
## v0.0.1 - 6/11/2010
Initial release
test:
@node test/ --integration $(TESTS)
test-unit:
@node test/ $(TESTS)
.PHONY: test test-unit
# gm v1.17.0 [![Build Status](https://travis-ci.org/aheckmann/gm.png?branch=master)](https://travis-ci.org/aheckmann/gm) [![NPM Version](https://img.shields.io/npm/v/gm.svg?style=flat)](https://www.npmjs.org/package/gm)
GraphicsMagick and ImageMagick for node
## Getting started
First download and install [GraphicsMagick](http://www.graphicsmagick.org/) or [ImageMagick](http://www.imagemagick.org/). In Mac OS X, you can simply use [Homebrew](http://mxcl.github.io/homebrew/) and do:
brew install imagemagick
brew install graphicsmagick
If you want WebP support with ImageMagick, you must add the WebP option:
brew install imagemagick --with-webp
then either use npm:
npm install gm
or clone the repo:
git clone git://github.com/aheckmann/gm.git
## Use ImageMagick instead of gm
Just pass the option `{imageMagick: true}` to enable ImageMagick
```js
var fs = require('fs')
, gm = require('./gm');
// resize and remove EXIF profile data
gm('/path/to/my/img.jpg')
.options({imageMagick: true})
.resize(240, 240)
...
```
## Basic Usage
```js
var fs = require('fs')
, gm = require('./gm');
// resize and remove EXIF profile data
gm('/path/to/my/img.jpg')
.resize(240, 240)
.noProfile()
.write('/path/to/resize.png', function (err) {
if (!err) console.log('done');
});
// obtain the size of an image
gm('/path/to/my/img.jpg')
.size(function (err, size) {
if (!err)
console.log(size.width > size.height ? 'wider' : 'taller than you');
});
// output all available image properties
gm('/path/to/img.png')
.identify(function (err, data) {
if (!err) console.log(data)
});
// pull out the first frame of an animated gif and save as png
gm('/path/to/animated.gif[0]')
.write('/path/to/firstframe.png', function (err) {
if (err) console.log('aaw, shucks');
});
// auto-orient an image
gm('/path/to/img.jpg')
.autoOrient()
.write('/path/to/oriented.jpg', function (err) {
if (err) ...
})
// crazytown
gm('/path/to/my/img.jpg')
.flip()
.magnify()
.rotate('green', 45)
.blur(7, 3)
.crop(300, 300, 150, 130)
.edge(3)
.write('/path/to/crazy.jpg', function (err) {
if (!err) console.log('crazytown has arrived');
})
// annotate an image
gm('/path/to/my/img.jpg')
.stroke("#ffffff")
.drawCircle(10, 10, 20, 10)
.font("Helvetica.ttf", 12)
.drawText(30, 20, "GMagick!")
.write("/path/to/drawing.png", function (err) {
if (!err) console.log('done');
});
// creating an image
gm(200, 400, "#ddff99f3")
.drawText(10, 50, "from scratch")
.write("/path/to/brandNewImg.jpg", function (err) {
// ...
});
```
## Streams
```js
// passing a stream
var readStream = fs.createReadStream('/path/to/my/img.jpg');
gm(readStream, 'img.jpg')
.write('/path/to/reformat.png', function (err) {
if (!err) console.log('done');
});
// can also stream output to a ReadableStream
// (can be piped to a local file or remote server)
gm('/path/to/my/img.jpg')
.resize('200', '200')
.stream(function (err, stdout, stderr) {
var writeStream = fs.createWriteStream('/path/to/my/resized.jpg');
stdout.pipe(writeStream);
});
// without a callback, .stream() returns a stream
// this is just a convenience wrapper for above.
var writeStream = fs.createWriteStream('/path/to/my/resized.jpg');
gm('/path/to/my/img.jpg')
.resize('200', '200')
.stream()
.pipe(writeStream);
// pass a format or filename to stream() and
// gm will provide image data in that format
gm('/path/to/my/img.jpg')
.stream('png', function (err, stdout, stderr) {
var writeStream = fs.createWriteStream('/path/to/my/reformated.png');
stdout.pipe(writeStream);
});
// or without the callback
var writeStream = fs.createWriteStream('/path/to/my/reformated.png');
gm('/path/to/my/img.jpg')
.stream('png')
.pipe(writeStream);
// combine the two for true streaming image processing
var readStream = fs.createReadStream('/path/to/my/img.jpg');
gm(readStream, 'img.jpg')
.resize('200', '200')
.stream(function (err, stdout, stderr) {
var writeStream = fs.createWriteStream('/path/to/my/resized.jpg');
stdout.pipe(writeStream);
});
// GOTCHA:
// when working with input streams and any 'identify'
// operation (size, format, etc), you must pass "{bufferStream: true}" if
// you also need to convert (write() or stream()) the image afterwards
// NOTE: this buffers the readStream in memory!
var readStream = fs.createReadStream('/path/to/my/img.jpg');
gm(readStream, 'img.jpg')
.size({bufferStream: true}, function(err, size) {
this.resize(size.width / 2, size.height / 2)
this.write('/path/to/resized.jpg', function (err) {
if (!err) console.log('done');
});
});
```
## Buffers
```js
// A buffer can be passed instead of a filepath as well
var buf = require('fs').readFileSync('/path/to/image.jpg');
gm(buf, 'image.jpg')
.noise('laplacian')
.write('/path/to/out.jpg', function (err) {
if (err) return handle(err);
console.log('Created an image from a Buffer!');
});
/*
A buffer can also be returned instead of a stream
The first argument to toBuffer is optional, it specifies the image format
*/
gm('img.jpg')
.resize(100, 100)
.toBuffer('PNG',function (err, buffer) {
if (err) return handle(err);
console.log('done!');
})
```
## Custom Arguments
If `gm` does not supply you with a method you need or does not work as you'd like, you can simply use `gm().in()` or `gm().out()` to set your own arguments.
- `gm().command()` - Custom command such as `identify` or `convert`
- `gm().in()` - Custom input arguments
- `gm().out()` - Custom output arguments
The command will be formatted in the following order:
1. `command` - ie `convert`
2. `in` - the input arguments
3. `source` - stdin or an image file
4. `out` - the output arguments
5. `output` - stdout or the image file to write to
For example, suppose you want the following command:
```bash
gm "convert" "label:Offline" "PNG:-"
```
However, using `gm().label()` may not work as intended for you:
```js
gm()
.label('Offline')
.stream();
```
would yield:
```bash
gm "convert" "-label" "\"Offline\"" "PNG:-"
```
Instead, you can use `gm().out()`:
```js
gm()
.out('label:Offline')
.stream();
```
which correctly yields:
```bash
gm "convert" "label:Offline" "PNG:-"
```
### Custom Identify Format String
When identifying an image, you may want to use a custom formatting string instead of using `-verbose`, which is quite slow.
You can use your own [formatting string](http://www.imagemagick.org/script/escape.php) when using `gm().identify(format, callback)`.
For example,
```js
gm('img.png').format(function (err, format) {
})
// is equivalent to
gm('img.png').identify('%m', function (err, format) {
})
```
since `%m` is the format option for getting the image file format.
## Platform differences
Please document and refer to any [platform or ImageMagick/GraphicsMagick issues/differences here](https://github.com/aheckmann/gm/wiki/GraphicsMagick-and-ImageMagick-versions).
## Examples:
Check out the [examples](http://github.com/aheckmann/gm/tree/master/examples/) directory to play around.
Also take a look at the [extending gm](http://wiki.github.com/aheckmann/gm/extending-gm)
page to see how to customize gm to your own needs.
## Constructor:
There are a few ways you can use the `gm` image constructor.
- 1) `gm(path)` When you pass a string as the first argument it is interpreted as the path to an image you intend to manipulate.
- 2) `gm(stream || buffer, [filename])` You may also pass a ReadableStream or Buffer as the first argument, with an optional file name for format inference.
- 3) `gm(width, height, [color])` When you pass two integer arguments, gm will create a new image on the fly with the provided dimensions and an optional background color. And you can still chain just like you do with pre-existing images too. See [here](http://github.com/aheckmann/gm/blob/master/examples/new.js) for an example.
## Methods
- getters
- [size](http://aheckmann.github.com/gm/docs.html#getters) - returns the size (WxH) of the image
- [orientation](http://aheckmann.github.com/gm/docs.html#orientation) - returns the EXIF orientation of the image
- [format](http://aheckmann.github.com/gm/docs.html#getters) - returns the image format (gif, jpeg, png, etc)
- [depth](http://aheckmann.github.com/gm/docs.html#getters) - returns the image color depth
- [color](http://aheckmann.github.com/gm/docs.html#getters) - returns the number of colors
- [res](http://aheckmann.github.com/gm/docs.html#getters) - returns the image resolution
- [filesize](http://aheckmann.github.com/gm/docs.html#getters) - returns image filesize
- [identify](http://aheckmann.github.com/gm/docs.html#getters) - returns all image data available. Takes an optional format string.
- manipulation
- [adjoin](http://aheckmann.github.com/gm/docs.html#adjoin)
- [affine](http://aheckmann.github.com/gm/docs.html#affine)
- [antialias](http://aheckmann.github.com/gm/docs.html#antialias)
- [append](http://aheckmann.github.com/gm/docs.html#append)
- [authenticate](http://aheckmann.github.com/gm/docs.html#authenticate)
- [autoOrient](http://aheckmann.github.com/gm/docs.html#autoOrient)
- [average](http://aheckmann.github.com/gm/docs.html#average)
- [backdrop](http://aheckmann.github.com/gm/docs.html#backdrop)
- [bitdepth](http://aheckmann.github.com/gm/docs.html#bitdepth)
- [blackThreshold](http://aheckmann.github.com/gm/docs.html#blackThreshold)
- [bluePrimary](http://aheckmann.github.com/gm/docs.html#bluePrimary)
- [blur](http://aheckmann.github.com/gm/docs.html#blur)
- [border](http://aheckmann.github.com/gm/docs.html#border)
- [borderColor](http://aheckmann.github.com/gm/docs.html#borderColor)
- [box](http://aheckmann.github.com/gm/docs.html#box)
- [channel](http://aheckmann.github.com/gm/docs.html#channel)
- [charcoal](http://aheckmann.github.com/gm/docs.html#charcoal)
- [chop](http://aheckmann.github.com/gm/docs.html#chop)
- [clip](http://aheckmann.github.com/gm/docs.html#clip)
- [coalesce](http://aheckmann.github.com/gm/docs.html#coalesce)
- [colors](http://aheckmann.github.com/gm/docs.html#colors)
- [colorize](http://aheckmann.github.com/gm/docs.html#colorize)
- [colorMap](http://aheckmann.github.com/gm/docs.html#colorMap)
- [colorspace](http://aheckmann.github.com/gm/docs.html#colorspace)
- [comment](http://aheckmann.github.com/gm/docs.html#comment)
- [compose](http://aheckmann.github.com/gm/docs.html#compose)
- [compress](http://aheckmann.github.com/gm/docs.html#compress)
- [contrast](http://aheckmann.github.com/gm/docs.html#contrast)
- [convolve](http://aheckmann.github.com/gm/docs.html#convolve)
- [createDirectories](http://aheckmann.github.com/gm/docs.html#createDirectories)
- [crop](http://aheckmann.github.com/gm/docs.html#crop)
- [cycle](http://aheckmann.github.com/gm/docs.html#cycle)
- [deconstruct](http://aheckmann.github.com/gm/docs.html#deconstruct)
- [delay](http://aheckmann.github.com/gm/docs.html#delay)
- [define](http://aheckmann.github.com/gm/docs.html#define)
- [density](http://aheckmann.github.com/gm/docs.html#density)
- [despeckle](http://aheckmann.github.com/gm/docs.html#despeckle)
- [dither](http://aheckmann.github.com/gm/docs.html#dither)
- [displace](http://aheckmann.github.com/gm/docs.html#dither)
- [display](http://aheckmann.github.com/gm/docs.html#display)
- [dispose](http://aheckmann.github.com/gm/docs.html#dispose)
- [dissolve](http://aheckmann.github.com/gm/docs.html#dissolve)
- [edge](http://aheckmann.github.com/gm/docs.html#edge)
- [emboss](http://aheckmann.github.com/gm/docs.html#emboss)
- [encoding](http://aheckmann.github.com/gm/docs.html#encoding)
- [enhance](http://aheckmann.github.com/gm/docs.html#enhance)
- [endian](http://aheckmann.github.com/gm/docs.html#endian)
- [equalize](http://aheckmann.github.com/gm/docs.html#equalize)
- [extent](http://aheckmann.github.com/gm/docs.html#extent)
- [file](http://aheckmann.github.com/gm/docs.html#file)
- [filter](http://aheckmann.github.com/gm/docs.html#filter)
- [flatten](http://aheckmann.github.com/gm/docs.html#flatten)
- [flip](http://aheckmann.github.com/gm/docs.html#flip)
- [flop](http://aheckmann.github.com/gm/docs.html#flop)
- [foreground](http://aheckmann.github.com/gm/docs.html#foreground)
- [frame](http://aheckmann.github.com/gm/docs.html#frame)
- [fuzz](http://aheckmann.github.com/gm/docs.html#fuzz)
- [gamma](http://aheckmann.github.com/gm/docs.html#gamma)
- [gaussian](http://aheckmann.github.com/gm/docs.html#gaussian)
- [geometry](http://aheckmann.github.com/gm/docs.html#geometry)
- [gravity](http://aheckmann.github.com/gm/docs.html#gravity)
- [greenPrimary](http://aheckmann.github.com/gm/docs.html#greenPrimary)
- [highlightColor](http://aheckmann.github.com/gm/docs.html#highlightColor)
- [highlightStyle](http://aheckmann.github.com/gm/docs.html#highlightStyle)
- [iconGeometry](http://aheckmann.github.com/gm/docs.html#iconGeometry)
- [implode](http://aheckmann.github.com/gm/docs.html#implode)
- [intent](http://aheckmann.github.com/gm/docs.html#intent)
- [interlace](http://aheckmann.github.com/gm/docs.html#interlace)
- [label](http://aheckmann.github.com/gm/docs.html#label)
- [lat](http://aheckmann.github.com/gm/docs.html#lat)
- [level](http://aheckmann.github.com/gm/docs.html#level)
- [list](http://aheckmann.github.com/gm/docs.html#list)
- [limit](http://aheckmann.github.com/gm/docs.html#limit)
- [log](http://aheckmann.github.com/gm/docs.html#log)
- [loop](http://aheckmann.github.com/gm/docs.html#loop)
- [lower](http://aheckmann.github.com/gm/docs.html#lower)
- [magnify](http://aheckmann.github.com/gm/docs.html#magnify)
- [map](http://aheckmann.github.com/gm/docs.html#map)
- [matte](http://aheckmann.github.com/gm/docs.html#matte)
- [matteColor](http://aheckmann.github.com/gm/docs.html#matteColor)
- [mask](http://aheckmann.github.com/gm/docs.html#mask)
- [maximumError](http://aheckmann.github.com/gm/docs.html#maximumError)
- [median](http://aheckmann.github.com/gm/docs.html#median)
- [minify](http://aheckmann.github.com/gm/docs.html#minify)
- [mode](http://aheckmann.github.com/gm/docs.html#mode)
- [modulate](http://aheckmann.github.com/gm/docs.html#modulate)
- [monitor](http://aheckmann.github.com/gm/docs.html#monitor)
- [monochrome](http://aheckmann.github.com/gm/docs.html#monochrome)
- [morph](http://aheckmann.github.com/gm/docs.html#morph)
- [mosaic](http://aheckmann.github.com/gm/docs.html#mosaic)
- [motionBlur](http://aheckmann.github.com/gm/docs.html#motionBlur)
- [name](http://aheckmann.github.com/gm/docs.html#name)
- [negative](http://aheckmann.github.com/gm/docs.html#negative)
- [noise](http://aheckmann.github.com/gm/docs.html#noise)
- [noop](http://aheckmann.github.com/gm/docs.html#noop)
- [normalize](http://aheckmann.github.com/gm/docs.html#normalize)
- [noProfile](http://aheckmann.github.com/gm/docs.html#profile)
- [opaque](http://aheckmann.github.com/gm/docs.html#opaque)
- [operator](http://aheckmann.github.com/gm/docs.html#operator)
- [orderedDither](http://aheckmann.github.com/gm/docs.html#orderedDither)
- [outputDirectory](http://aheckmann.github.com/gm/docs.html#outputDirectory)
- [paint](http://aheckmann.github.com/gm/docs.html#paint)
- [page](http://aheckmann.github.com/gm/docs.html#page)
- [pause](http://aheckmann.github.com/gm/docs.html#pause)
- [pen](http://aheckmann.github.com/gm/docs.html#pen)
- [ping](http://aheckmann.github.com/gm/docs.html#ping)
- [pointSize](http://aheckmann.github.com/gm/docs.html#pointSize)
- [preview](http://aheckmann.github.com/gm/docs.html#preview)
- [process](http://aheckmann.github.com/gm/docs.html#process)
- [profile](http://aheckmann.github.com/gm/docs.html#profile)
- [progress](http://aheckmann.github.com/gm/docs.html#progress)
- [quality](http://aheckmann.github.com/gm/docs.html#quality)
- [raise](http://aheckmann.github.com/gm/docs.html#raise)
- [rawSize](http://aheckmann.github.com/gm/docs.html#rawSize)
- [randomThreshold](http://aheckmann.github.com/gm/docs.html#randomThreshold)
- [recolor](http://aheckmann.github.com/gm/docs.html#recolor)
- [redPrimary](http://aheckmann.github.com/gm/docs.html#redPrimary)
- [region](http://aheckmann.github.com/gm/docs.html#region)
- [remote](http://aheckmann.github.com/gm/docs.html#remote)
- [render](http://aheckmann.github.com/gm/docs.html#render)
- [repage](http://aheckmann.github.com/gm/docs.html#repage)
- [resample](http://aheckmann.github.com/gm/docs.html#resample)
- [resize](http://aheckmann.github.com/gm/docs.html#resize)
- [roll](http://aheckmann.github.com/gm/docs.html#roll)
- [rotate](http://aheckmann.github.com/gm/docs.html#rotate)
- [sample](http://aheckmann.github.com/gm/docs.html#sample)
- [samplingFactor](http://aheckmann.github.com/gm/docs.html#samplingFactor)
- [scale](http://aheckmann.github.com/gm/docs.html#scale)
- [scene](http://aheckmann.github.com/gm/docs.html#scene)
- [scenes](http://aheckmann.github.com/gm/docs.html#scenes)
- [screen](http://aheckmann.github.com/gm/docs.html#screen)
- [segment](http://aheckmann.github.com/gm/docs.html#segment)
- [sepia](http://aheckmann.github.com/gm/docs.html#sepia)
- [set](http://aheckmann.github.com/gm/docs.html#set)
- [setFormat](http://aheckmann.github.com/gm/docs.html#setformat)
- [shade](http://aheckmann.github.com/gm/docs.html#shade)
- [shadow](http://aheckmann.github.com/gm/docs.html#shadow)
- [sharedMemory](http://aheckmann.github.com/gm/docs.html#sharedMemory)
- [sharpen](http://aheckmann.github.com/gm/docs.html#sharpen)
- [shave](http://aheckmann.github.com/gm/docs.html#shave)
- [shear](http://aheckmann.github.com/gm/docs.html#shear)
- [silent](http://aheckmann.github.com/gm/docs.html#silent)
- [solarize](http://aheckmann.github.com/gm/docs.html#solarize)
- [snaps](http://aheckmann.github.com/gm/docs.html#snaps)
- [stegano](http://aheckmann.github.com/gm/docs.html#stegano)
- [stereo](http://aheckmann.github.com/gm/docs.html#stereo)
- [strip](http://aheckmann.github.com/gm/docs.html#strip) _imagemagick only_
- [spread](http://aheckmann.github.com/gm/docs.html#spread)
- [swirl](http://aheckmann.github.com/gm/docs.html#swirl)
- [textFont](http://aheckmann.github.com/gm/docs.html#textFont)
- [texture](http://aheckmann.github.com/gm/docs.html#texture)
- [threshold](http://aheckmann.github.com/gm/docs.html#threshold)
- [thumb](http://aheckmann.github.com/gm/docs.html#thumb)
- [tile](http://aheckmann.github.com/gm/docs.html#tile)
- [transform](http://aheckmann.github.com/gm/docs.html#transform)
- [transparent](http://aheckmann.github.com/gm/docs.html#transparent)
- [treeDepth](http://aheckmann.github.com/gm/docs.html#treeDepth)
- [trim](http://aheckmann.github.com/gm/docs.html#trim)
- [type](http://aheckmann.github.com/gm/docs.html#type)
- [update](http://aheckmann.github.com/gm/docs.html#update)
- [units](http://aheckmann.github.com/gm/docs.html#units)
- [unsharp](http://aheckmann.github.com/gm/docs.html#unsharp)
- [usePixmap](http://aheckmann.github.com/gm/docs.html#usePixmap)
- [view](http://aheckmann.github.com/gm/docs.html#view)
- [virtualPixel](http://aheckmann.github.com/gm/docs.html#virtualPixel)
- [visual](http://aheckmann.github.com/gm/docs.html#visual)
- [watermark](http://aheckmann.github.com/gm/docs.html#watermark)
- [wave](http://aheckmann.github.com/gm/docs.html#wave)
- [whitePoint](http://aheckmann.github.com/gm/docs.html#whitePoint)
- [whiteThreshold](http://aheckmann.github.com/gm/docs.html#whiteThreshold)
- [window](http://aheckmann.github.com/gm/docs.html#window)
- [windowGroup](http://aheckmann.github.com/gm/docs.html#windowGroup)
- drawing primitives
- [draw](http://aheckmann.github.com/gm/docs.html#draw)
- [drawArc](http://aheckmann.github.com/gm/docs.html#drawArc)
- [drawBezier](http://aheckmann.github.com/gm/docs.html#drawBezier)
- [drawCircle](http://aheckmann.github.com/gm/docs.html#drawCircle)
- [drawEllipse](http://aheckmann.github.com/gm/docs.html#drawEllipse)
- [drawLine](http://aheckmann.github.com/gm/docs.html#drawLine)
- [drawPoint](http://aheckmann.github.com/gm/docs.html#drawPoint)
- [drawPolygon](http://aheckmann.github.com/gm/docs.html#drawPolygon)
- [drawPolyline](http://aheckmann.github.com/gm/docs.html#drawPolyline)
- [drawRectangle](http://aheckmann.github.com/gm/docs.html#drawRectangle)
- [drawText](http://aheckmann.github.com/gm/docs.html#drawText)
- [fill](http://aheckmann.github.com/gm/docs.html#fill)
- [font](http://aheckmann.github.com/gm/docs.html#font)
- [fontSize](http://aheckmann.github.com/gm/docs.html#fontSize)
- [stroke](http://aheckmann.github.com/gm/docs.html#stroke)
- [strokeWidth](http://aheckmann.github.com/gm/docs.html#strokeWidth)
- [setDraw](http://aheckmann.github.com/gm/docs.html#setDraw)
- image output
- **write** - writes the processed image data to the specified filename
- **stream** - provides a `ReadableStream` with the processed image data
- **toBuffer** - returns the image as a `Buffer` instead of a stream
##compare
Graphicsmagicks `compare` command is exposed through `gm.compare()`. This allows us to determine if two images can be considered "equal".
Currently `gm.compare` only accepts file paths.
gm.compare(path1, path2 [, options], callback)
```js
gm.compare('/path/to/image1.jpg', '/path/to/another.png', function (err, isEqual, equality, raw, path1, path2) {
if (err) return handle(err);
// if the images were considered equal, `isEqual` will be true, otherwise, false.
console.log('The images were equal: %s', isEqual);
// to see the total equality returned by graphicsmagick we can inspect the `equality` argument.
console.log('Actual equality: %d', equality);
// inspect the raw output
console.log(raw);
// print file paths
console.log(path1, path2);
})
```
You may wish to pass a custom tolerance threshold to increase or decrease the default level of `0.4`.
```js
gm.compare('/path/to/image1.jpg', '/path/to/another.png', 1.2, function (err, isEqual) {
...
})
```
To output a diff image, pass a configuration object to define the diff options and tolerance.
```js
var options = {
file: '/path/to/diff.png',
highlightColor: 'yellow',
tolerance: 0.02
}
gm.compare('/path/to/image1.jpg', '/path/to/another.png', options, function (err, isEqual, equality, raw) {
...
})
```
##composite
GraphicsMagick supports compositing one image on top of another. This is exposed through `gm.composite()`. Its first argument is an image path with the changes to the base image, and an optional mask image.
Currently, `gm.composite()` only accepts file paths.
gm.composite(other [, mask])
```js
gm('/path/to/image.jpg')
.composite('/path/to/second_image.jpg')
.geometry('+100+150')
.write('/path/to/composite.png', function(err) {
if(!err) console.log("Written composite image.");
});
```
## Contributors
[https://github.com/aheckmann/gm/contributors](https://github.com/aheckmann/gm/contributors)
## Inspiration
http://github.com/quiiver/magickal-node
## Plugins
[https://github.com/aheckmann/gm/wiki](https://github.com/aheckmann/gm/wiki)
## License
(The MIT License)
Copyright (c) 2010 [Aaron Heckmann](aaron.heckmann+github@gmail.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.
/**
* Module dependencies.
*/
var Stream = require('stream').Stream;
var EventEmitter = require('events').EventEmitter;
var util = require('util');
util.inherits(gm, EventEmitter);
/**
* Constructor.
*
* @param {String|Number} path - path to img source or ReadableStream or width of img to create
* @param {Number} [height] - optional filename of ReadableStream or height of img to create
* @param {String} [color] - optional hex background color of created img
*/
function gm (source, height, color) {
var width;
if (!(this instanceof gm)) {
return new gm(source, height, color);
}
EventEmitter.call(this);
this._options = {};
this.options(this.__proto__._options);
this.data = {};
this._in = [];
this._out = [];
this._outputFormat = null;
this._subCommand = 'convert';
if (source instanceof Stream) {
this.sourceStream = source;
source = height || 'unknown.jpg';
} else if (Buffer.isBuffer(source)) {
this.sourceBuffer = source;
source = height || 'unknown.jpg';
} else if (height) {
// new images
width = source;
source = "";
this.in("-size", width + "x" + height);
if (color) {
this.in("xc:"+ color);
}
}
if (typeof source === "string") {
// then source is a path
// parse out gif frame brackets from filename
// since stream doesn't use source path
// eg. "filename.gif[0]"
var frames = source.match(/(\[.+\])$/);
if (frames) {
this.sourceFrames = source.substr(frames.index, frames[0].length);
source = source.substr(0, frames.index);
}
}
this.source = source;
this.addSrcFormatter(function (src) {
// must be first source formatter
var inputFromStdin = this.sourceStream || this.sourceBuffer;
var ret = inputFromStdin ? '-' : this.source;
if (ret && this.sourceFrames) ret += this.sourceFrames;
src.length = 0;
src[0] = ret;
});
}
/**
* Subclasses the gm constructor with custom options.
*
* @param {options} options
* @return {gm} the subclasses gm constructor
*/
var parent = gm;
gm.subClass = function subClass (options) {
function gm (source, height, color) {
if (!(this instanceof parent)) {
return new gm(source, height, color);
}
parent.call(this, source, height, color);
}
gm.prototype.__proto__ = parent.prototype;
gm.prototype._options = {};
gm.prototype.options(options);
return gm;
}
/**
* Augment the prototype.
*/
require("./lib/options")(gm.prototype);
require("./lib/getters")(gm);
require("./lib/args")(gm.prototype);
require("./lib/drawing")(gm.prototype);
require("./lib/convenience")(gm.prototype);
require("./lib/command")(gm.prototype);
require("./lib/compare")(gm.prototype);
require("./lib/composite")(gm.prototype);
/**
* Expose.
*/
module.exports = exports = gm;
module.exports.utils = require('./lib/utils');
module.exports.compare = require('./lib/compare')();
module.exports.version = JSON.parse(
require('fs').readFileSync(__dirname + '/package.json', 'utf8')
).version;
# Compiled source #
###################
*.com
*.class
*.dll
*.exe
*.o
*.so
# Packages #
############
# it's better to unpack these files and commit the raw source
# git has its own built in compression methods
*.7z
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
# Logs and databases #
######################
*.log
*.sql
*.sqlite
# OS generated files #
######################
.DS_Store*
ehthumbs.db
Icon?
Thumbs.db
# Node.js #
###########
lib-cov
*.seed
*.log
*.csv
*.dat
*.out
*.pid
*.gz
pids
logs
results
node_modules
npm-debug.log
# Components #
##############
/build
/components
\ No newline at end of file
language: node_js
node_js:
- "0.4"
- "0.6"
- "0.8"
- "0.10"
\ No newline at end of file
# Array Series [![Build Status](https://travis-ci.org/component/array-parallel.png)](https://travis-ci.org/component/array-parallel)
Call an array of asynchronous functions in parallel
### API
#### parallel(fns[, context[, callback]])
```js
var parallel = require('array-parallel')
parallel([
function (done) {
done()
}
], this, function (err) {
})
```
#### fns
`fns` is an array of functions to call in parallel.
The argument signature should be:
```js
function (done) {
done(new Error())
// or
done(null, result)
}
```
That is, each function should only take a `done` as an argument.
Each callback should only take an `Error` as the first argument,
or a value as the second.
#### context
Optional context to pass to each `fn`.
Basically `fn.call(context, done)`.
#### callback(err, results)
```js
function (err, results) {
}
```
Only argument is an `Error` argument.
It will be the first error retrieved from all the `fns`.
`results` will be an array of results from each `fn`,
thus this could be considered an asynchronous version of `[].map`.
### License
The MIT License (MIT)
Copyright (c) 2013 Jonathan Ong me@jongleberry.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.
{
"name": "array-parallel",
"description": "Call an array of asynchronous functions in parallel",
"repo": "array-parallel",
"version": "0.1.3",
"main": "index.js",
"scripts": [
"index.js"
],
"license": "MIT"
}
\ No newline at end of file
module.exports = function parallel(fns, context, callback) {
if (!callback) {
if (typeof context === 'function') {
callback = context
context = null
} else {
callback = noop
}
}
var pending = fns && fns.length
if (!pending) return callback(null, []);
var finished = false
var results = new Array(pending)
fns.forEach(context ? function (fn, i) {
fn.call(context, maybeDone(i))
} : function (fn, i) {
fn(maybeDone(i))
})
function maybeDone(i) {
return function (err, result) {
if (finished) return;
if (err) {
callback(err, results)
finished = true
return
}
results[i] = result
if (!--pending) callback(null, results);
}
}
}
function noop() {}
{
"name": "array-parallel",
"description": "Call an array of asynchronous functions in parallel",
"version": "0.1.3",
"scripts": {
"test": "node test"
},
"author": {
"name": "Jonathan Ong",
"email": "me@jongleberry.com",
"url": "http://jongleberry.com"
},
"repository": {
"type": "git",
"url": "https://github.com/component/array-parallel.git"
},
"bugs": {
"url": "https://github.com/component/array-parallel/issues",
"email": "me@jongleberry.com"
},
"license": "MIT",
"homepage": "https://github.com/component/array-parallel",
"_id": "array-parallel@0.1.3",
"dist": {
"shasum": "8f785308926ed5aa478c47e64d1b334b6c0c947d",
"tarball": "http://registry.npmjs.org/array-parallel/-/array-parallel-0.1.3.tgz"
},
"_from": "array-parallel@~0.1.0",
"_npmVersion": "1.3.17",
"_npmUser": {
"name": "jongleberry",
"email": "jonathanrichardong@gmail.com"
},
"maintainers": [
{
"name": "jongleberry",
"email": "jonathanrichardong@gmail.com"
}
],
"directories": {},
"_shasum": "8f785308926ed5aa478c47e64d1b334b6c0c947d",
"_resolved": "https://registry.npmjs.org/array-parallel/-/array-parallel-0.1.3.tgz"
}
var assert = require('assert')
var parallel = require('./')
var a, b, c
parallel([
function (done) {
setTimeout(function () {
done(null, a = 0)
}, 5)
},
function (done) {
setTimeout(function () {
done(null, b = 1)
}, 10)
},
function (done) {
setTimeout(function () {
done(null, c = 2)
}, 15)
}
], function (err, results) {
assert.equal(a, 0)
assert.equal(b, 1)
assert.equal(c, 2)
assert.deepEqual(results, [0, 1, 2])
})
var d, e
parallel([
function (done) {
setTimeout(function () {
d = 1
done(new Error('message'))
}, 5)
},
function (done) {
setTimeout(function () {
e = 2
done()
}, 10)
}
], function (err) {
assert.equal(err.message, 'message')
assert.equal(d, 1)
assert.equal(e, undefined)
})
var context = 'hello'
parallel([function (done) {
assert.equal(this, context)
}], context)
var f
parallel([function (done) {
f = true
done()
}])
process.nextTick(function () {
assert.equal(f, true)
})
\ No newline at end of file
# Compiled source #
###################
*.com
*.class
*.dll
*.exe
*.o
*.so
# Packages #
############
# it's better to unpack these files and commit the raw source
# git has its own built in compression methods
*.7z
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
# Logs and databases #
######################
*.log
*.sql
*.sqlite
# OS generated files #
######################
.DS_Store*
ehthumbs.db
Icon?
Thumbs.db
# Node.js #
###########
lib-cov
*.seed
*.log
*.csv
*.dat
*.out
*.pid
*.gz
pids
logs
results
node_modules
npm-debug.log
# Components #
##############
/build
/components
\ No newline at end of file
language: node_js
node_js:
- "0.8"
- "0.10"
\ No newline at end of file
# Array Series [![Build Status](https://travis-ci.org/component/array-series.png)](https://travis-ci.org/component/array-series)
Call an array of asynchronous functions in series
### API
#### series(fns[, context[, callback]])
```js
var series = require('array-series')
series([
function (done) {
done()
}
], this, function (err) {
})
```
#### fns
`fns` is an array of functions to call in series.
The argument signature should be:
```js
function (done) {
done(new Error())
// or
done()
}
```
That is, each function should only take a `done` as an argument.
Each callback should only take an optional `Error` as an argument.
#### context
Optional context to pass to each `fn`.
Basically `fn.call(context, done)`.
#### callback(err)
```js
function (err) {
}
```
Only argument is an `Error` argument.
It will return the first error in the series of functions that returns an error,
and no function after will be called.
### License
The MIT License (MIT)
Copyright (c) 2013 Jonathan Ong me@jongleberry.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.
\ No newline at end of file
{
"name": "array-series",
"description": "Call an array of asynchronous functions in series",
"repo": "component/array-series",
"version": "0.1.5",
"main": "index.js",
"scripts": [
"index.js"
],
"license": "MIT"
}
\ No newline at end of file
module.exports = function series(fns, context, callback) {
if (!callback) {
if (typeof context === 'function') {
callback = context
context = null
} else {
callback = noop
}
}
if (!(fns && fns.length)) return callback();
fns = fns.slice(0)
var call = context
? function () {
fns.length
? fns.shift().call(context, next)
: callback()
}
: function () {
fns.length
? fns.shift()(next)
: callback()
}
call()
function next(err) {
err ? callback(err) : call()
}
}
function noop() {}
{
"name": "array-series",
"description": "Call an array of asynchronous functions in series",
"version": "0.1.5",
"scripts": {
"test": "node test"
},
"author": {
"name": "Jonathan Ong",
"email": "me@jongleberry.com",
"url": "http://jongleberry.com"
},
"repository": {
"type": "git",
"url": "https://github.com/component/array-series.git"
},
"bugs": {
"url": "https://github.com/component/array-series/issues",
"email": "me@jongleberry.com"
},
"license": "MIT",
"homepage": "https://github.com/component/array-series",
"_id": "array-series@0.1.5",
"dist": {
"shasum": "df5d37bfc5c2ef0755e2aa4f92feae7d4b5a972f",
"tarball": "http://registry.npmjs.org/array-series/-/array-series-0.1.5.tgz"
},
"_from": "array-series@~0.1.0",
"_npmVersion": "1.3.17",
"_npmUser": {
"name": "jongleberry",
"email": "jonathanrichardong@gmail.com"
},
"maintainers": [
{
"name": "jongleberry",
"email": "jonathanrichardong@gmail.com"
}
],
"directories": {},
"_shasum": "df5d37bfc5c2ef0755e2aa4f92feae7d4b5a972f",
"_resolved": "https://registry.npmjs.org/array-series/-/array-series-0.1.5.tgz"
}
var assert = require('assert')
var series = require('./')
var a, b, c
series([
function (done) {
a = 1
process.nextTick(done)
check('a')
},
function (done) {
b = 2
process.nextTick(done)
check('b')
},
function (done) {
c = 3
process.nextTick(done)
check('c')
}
], function (err) {
assert.ifError(err)
assert.equal(a, 1)
assert.equal(b, 2)
assert.equal(c, 3)
})
function check(x) {
switch (x) {
case 'a':
assert.equal(a, 1)
assert.equal(b, undefined)
assert.equal(c, undefined)
break
case 'b':
assert.equal(a, 1)
assert.equal(b, 2)
assert.equal(c, undefined)
break
case 'c':
assert.equal(a, 1)
assert.equal(b, 2)
assert.equal(c, 3)
break
}
}
var context = 'hello'
series([function (done) {
assert.equal(this, context)
done()
}], context)
var finished
series([], function (err) {
finished = true
})
process.nextTick(function () {
if (!finished)
throw new Error('Failed with no functions.');
})
var r, d, o
series([
function (done) {
r = 1
process.nextTick(done)
},
function (done) {
d = 0
process.nextTick(function () {
done(new Error('message'))
})
},
function (done) {
o = 0
process.nextTick(done)
}
], function (err) {
assert.equal(err.message, 'message')
assert.equal(r, 1)
assert.equal(d, 0)
assert.equal(o, undefined)
})
console.log('Array series tests pass!')
\ No newline at end of file
0.7.0 / 2012-05-04
==================
* Added .component to package.json
* Added debug.component.js build
0.6.0 / 2012-03-16
==================
* Added support for "-" prefix in DEBUG [Vinay Pulim]
* Added `.enabled` flag to the node version [TooTallNate]
0.5.0 / 2012-02-02
==================
* Added: humanize diffs. Closes #8
* Added `debug.disable()` to the CS variant
* Removed padding. Closes #10
* Fixed: persist client-side variant again. Closes #9
0.4.0 / 2012-02-01
==================
* Added browser variant support for older browsers [TooTallNate]
* Added `debug.enable('project:*')` to browser variant [TooTallNate]
* Added padding to diff (moved it to the right)
0.3.0 / 2012-01-26
==================
* Added millisecond diff when isatty, otherwise UTC string
0.2.0 / 2012-01-22
==================
* Added wildcard support
0.1.0 / 2011-12-02
==================
* Added: remove colors unless stderr isatty [TooTallNate]
0.0.1 / 2010-01-03
==================
* Initial release
debug.component.js: head.js debug.js tail.js
cat $^ > $@
# debug
tiny node.js debugging utility.
## Installation
```
$ npm install debug
```
## Example
This module is modelled after node core's debugging technique, allowing you to enable one or more topic-specific debugging functions, for example core does the following within many modules:
```js
var debug;
if (process.env.NODE_DEBUG && /cluster/.test(process.env.NODE_DEBUG)) {
debug = function(x) {
var prefix = process.pid + ',' +
(process.env.NODE_WORKER_ID ? 'Worker' : 'Master');
console.error(prefix, x);
};
} else {
debug = function() { };
}
```
This concept is extremely simple but it works well. With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility.
Example _app.js_:
```js
var debug = require('debug')('http')
, http = require('http')
, name = 'My App';
// fake app
debug('booting %s', name);
http.createServer(function(req, res){
debug(req.method + ' ' + req.url);
res.end('hello\n');
}).listen(3000, function(){
debug('listening');
});
// fake worker of some kind
require('./worker');
```
Example _worker.js_:
```js
var debug = require('debug')('worker');
setInterval(function(){
debug('doing some work');
}, 1000);
```
The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples:
![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png)
![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png)
## Millisecond diff
When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls.
![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png)
When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below:
![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png)
## Conventions
If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser".
## Wildcards
The "*" character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.
You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=* -connect:*` would include all debuggers except those starting with "connect:".
## Browser support
Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`.
```js
a = debug('worker:a');
b = debug('worker:b');
setInterval(function(){
a('doing some work');
}, 1000);
setInterval(function(){
a('doing some work');
}, 1200);
```
## License
(The MIT License)
Copyright (c) 2011 TJ Holowaychuk &lt;tj@vision-media.ca&gt;
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.
\ No newline at end of file
;(function(){
/**
* Create a debugger with the given `name`.
*
* @param {String} name
* @return {Type}
* @api public
*/
function debug(name) {
if (!debug.enabled(name)) return function(){};
return function(fmt){
var curr = new Date;
var ms = curr - (debug[name] || curr);
debug[name] = curr;
fmt = name
+ ' '
+ fmt
+ ' +' + debug.humanize(ms);
// This hackery is required for IE8
// where `console.log` doesn't have 'apply'
window.console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
}
/**
* The currently active debug mode names.
*/
debug.names = [];
debug.skips = [];
/**
* Enables a debug mode by name. This can include modes
* separated by a colon and wildcards.
*
* @param {String} name
* @api public
*/
debug.enable = function(name) {
localStorage.debug = name;
var split = (name || '').split(/[\s,]+/)
, len = split.length;
for (var i = 0; i < len; i++) {
name = split[i].replace('*', '.*?');
if (name[0] === '-') {
debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
}
else {
debug.names.push(new RegExp('^' + name + '$'));
}
}
};
/**
* Disable debug output.
*
* @api public
*/
debug.disable = function(){
debug.enable('');
};
/**
* Humanize the given `ms`.
*
* @param {Number} m
* @return {String}
* @api private
*/
debug.humanize = function(ms) {
var sec = 1000
, min = 60 * 1000
, hour = 60 * min;
if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
if (ms >= min) return (ms / min).toFixed(1) + 'm';
if (ms >= sec) return (ms / sec | 0) + 's';
return ms + 'ms';
};
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
debug.enabled = function(name) {
for (var i = 0, len = debug.skips.length; i < len; i++) {
if (debug.skips[i].test(name)) {
return false;
}
}
for (var i = 0, len = debug.names.length; i < len; i++) {
if (debug.names[i].test(name)) {
return true;
}
}
return false;
};
// persist
if (window.localStorage) debug.enable(localStorage.debug);
module.exports = debug;
})();
\ No newline at end of file
/**
* Create a debugger with the given `name`.
*
* @param {String} name
* @return {Type}
* @api public
*/
function debug(name) {
if (!debug.enabled(name)) return function(){};
return function(fmt){
var curr = new Date;
var ms = curr - (debug[name] || curr);
debug[name] = curr;
fmt = name
+ ' '
+ fmt
+ ' +' + debug.humanize(ms);
// This hackery is required for IE8
// where `console.log` doesn't have 'apply'
window.console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
}
/**
* The currently active debug mode names.
*/
debug.names = [];
debug.skips = [];
/**
* Enables a debug mode by name. This can include modes
* separated by a colon and wildcards.
*
* @param {String} name
* @api public
*/
debug.enable = function(name) {
localStorage.debug = name;
var split = (name || '').split(/[\s,]+/)
, len = split.length;
for (var i = 0; i < len; i++) {
name = split[i].replace('*', '.*?');
if (name[0] === '-') {
debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
}
else {
debug.names.push(new RegExp('^' + name + '$'));
}
}
};
/**
* Disable debug output.
*
* @api public
*/
debug.disable = function(){
debug.enable('');
};
/**
* Humanize the given `ms`.
*
* @param {Number} m
* @return {String}
* @api private
*/
debug.humanize = function(ms) {
var sec = 1000
, min = 60 * 1000
, hour = 60 * min;
if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
if (ms >= min) return (ms / min).toFixed(1) + 'm';
if (ms >= sec) return (ms / sec | 0) + 's';
return ms + 'ms';
};
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
debug.enabled = function(name) {
for (var i = 0, len = debug.skips.length; i < len; i++) {
if (debug.skips[i].test(name)) {
return false;
}
}
for (var i = 0, len = debug.names.length; i < len; i++) {
if (debug.names[i].test(name)) {
return true;
}
}
return false;
};
// persist
if (window.localStorage) debug.enable(localStorage.debug);
\ No newline at end of file
var debug = require('../')('http')
, http = require('http')
, name = 'My App';
// fake app
debug('booting %s', name);
http.createServer(function(req, res){
debug(req.method + ' ' + req.url);
res.end('hello\n');
}).listen(3000, function(){
debug('listening');
});
// fake worker of some kind
require('./worker');
\ No newline at end of file
<html>
<head>
<title>debug()</title>
<script src="../debug.js"></script>
<script>
// type debug.enable('*') in
// the console and refresh :)
a = debug('worker:a');
b = debug('worker:b');
setInterval(function(){
a('doing some work');
}, 1000);
setInterval(function(){
a('doing some work');
}, 1200);
</script>
</head>
<body>
</body>
</html>
var debug = {
foo: require('../')('test:foo'),
bar: require('../')('test:bar'),
baz: require('../')('test:baz')
};
debug.foo('foo')
debug.bar('bar')
debug.baz('baz')
\ No newline at end of file
// DEBUG=* node example/worker
// DEBUG=worker:* node example/worker
// DEBUG=worker:a node example/worker
// DEBUG=worker:b node example/worker
var a = require('../')('worker:a')
, b = require('../')('worker:b');
function work() {
a('doing lots of uninteresting work');
setTimeout(work, Math.random() * 1000);
}
work();
function workb() {
b('doing some work');
setTimeout(workb, Math.random() * 2000);
}
workb();
\ No newline at end of file
module.exports = require('./lib/debug');
\ No newline at end of file
{
"name": "debug",
"version": "0.7.0",
"description": "small debugging utility",
"keywords": [
"debug",
"log",
"debugger"
],
"author": {
"name": "TJ Holowaychuk",
"email": "tj@vision-media.ca"
},
"dependencies": {},
"devDependencies": {
"mocha": "*"
},
"main": "index",
"browserify": "debug.component.js",
"engines": {
"node": "*"
},
"component": {
"scripts": {
"debug": "debug.component.js"
}
},
"_id": "debug@0.7.0",
"dist": {
"shasum": "f5be05ec0434c992d79940e50b2695cfb2e01b08",
"tarball": "http://registry.npmjs.org/debug/-/debug-0.7.0.tgz"
},
"maintainers": [
{
"name": "tjholowaychuk",
"email": "tj@vision-media.ca"
}
],
"directories": {},
"_shasum": "f5be05ec0434c992d79940e50b2695cfb2e01b08",
"_from": "debug@0.7.0",
"_resolved": "https://registry.npmjs.org/debug/-/debug-0.7.0.tgz"
}
module.exports = debug;
})();
\ No newline at end of file
Apache License, Version 2.0
Copyright (c) 2011 Dominic Tarr
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.
The MIT License
Copyright (c) 2011 Dominic Tarr
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 Stream = require('stream')
// through
//
// a stream that does nothing but re-emit the input.
// useful for aggregating a series of changing but not ending streams into one stream)
exports = module.exports = through
through.through = through
//create a readable writable stream.
function through (write, end, opts) {
write = write || function (data) { this.queue(data) }
end = end || function () { this.queue(null) }
var ended = false, destroyed = false, buffer = [], _ended = false
var stream = new Stream()
stream.readable = stream.writable = true
stream.paused = false
// stream.autoPause = !(opts && opts.autoPause === false)
stream.autoDestroy = !(opts && opts.autoDestroy === false)
stream.write = function (data) {
write.call(this, data)
return !stream.paused
}
function drain() {
while(buffer.length && !stream.paused) {
var data = buffer.shift()
if(null === data)
return stream.emit('end')
else
stream.emit('data', data)
}
}
stream.queue = stream.push = function (data) {
// console.error(ended)
if(_ended) return stream
if(data == null) _ended = true
buffer.push(data)
drain()
return stream
}
//this will be registered as the first 'end' listener
//must call destroy next tick, to make sure we're after any
//stream piped from here.
//this is only a problem if end is not emitted synchronously.
//a nicer way to do this is to make sure this is the last listener for 'end'
stream.on('end', function () {
stream.readable = false
if(!stream.writable && stream.autoDestroy)
process.nextTick(function () {
stream.destroy()
})
})
function _end () {
stream.writable = false
end.call(stream)
if(!stream.readable && stream.autoDestroy)
stream.destroy()
}
stream.end = function (data) {
if(ended) return
ended = true
if(arguments.length) stream.write(data)
_end() // will emit or queue
return stream
}
stream.destroy = function () {
if(destroyed) return
destroyed = true
ended = true
buffer.length = 0
stream.writable = stream.readable = false
stream.emit('close')
return stream
}
stream.pause = function () {
if(stream.paused) return
stream.paused = true
return stream
}
stream.resume = function () {
if(stream.paused) {
stream.paused = false
stream.emit('resume')
}
drain()
//may have become paused again,
//as drain emits 'data'.
if(!stream.paused)
stream.emit('drain')
return stream
}
return stream
}
{
"name": "through",
"version": "2.3.6",
"description": "simplified stream construction",
"main": "index.js",
"scripts": {
"test": "set -e; for t in test/*.js; do node $t; done"
},
"devDependencies": {
"stream-spec": "~0.3.5",
"tape": "~2.3.2",
"from": "~0.1.3"
},
"keywords": [
"stream",
"streams",
"user-streams",
"pipe"
],
"author": {
"name": "Dominic Tarr",
"email": "dominic.tarr@gmail.com",
"url": "dominictarr.com"
},
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/dominictarr/through.git"
},
"homepage": "http://github.com/dominictarr/through",
"testling": {
"browsers": [
"ie/8..latest",
"ff/15..latest",
"chrome/20..latest",
"safari/5.1..latest"
],
"files": "test/*.js"
},
"gitHead": "19ed9b7e84efe7c3e3c8be80f29390b1620e13c0",
"bugs": {
"url": "https://github.com/dominictarr/through/issues"
},
"_id": "through@2.3.6",
"_shasum": "26681c0f524671021d4e29df7c36bce2d0ecf2e8",
"_from": "through@~2.3.1",
"_npmVersion": "1.4.26",
"_npmUser": {
"name": "dominictarr",
"email": "dominic.tarr@gmail.com"
},
"maintainers": [
{
"name": "dominictarr",
"email": "dominic.tarr@gmail.com"
}
],
"dist": {
"shasum": "26681c0f524671021d4e29df7c36bce2d0ecf2e8",
"tarball": "http://registry.npmjs.org/through/-/through-2.3.6.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/through/-/through-2.3.6.tgz"
}
#through
[![build status](https://secure.travis-ci.org/dominictarr/through.png)](http://travis-ci.org/dominictarr/through)
[![testling badge](https://ci.testling.com/dominictarr/through.png)](https://ci.testling.com/dominictarr/through)
Easy way to create a `Stream` that is both `readable` and `writable`.
* Pass in optional `write` and `end` methods.
* `through` takes care of pause/resume logic if you use `this.queue(data)` instead of `this.emit('data', data)`.
* Use `this.pause()` and `this.resume()` to manage flow.
* Check `this.paused` to see current flow state. (`write` always returns `!this.paused`).
This function is the basis for most of the synchronous streams in
[event-stream](http://github.com/dominictarr/event-stream).
``` js
var through = require('through')
through(function write(data) {
this.queue(data) //data *must* not be null
},
function end () { //optional
this.queue(null)
})
```
Or, can also be used _without_ buffering on pause, use `this.emit('data', data)`,
and this.emit('end')
``` js
var through = require('through')
through(function write(data) {
this.emit('data', data)
//this.pause()
},
function end () { //optional
this.emit('end')
})
```
## Extended Options
You will probably not need these 99% of the time.
### autoDestroy=false
By default, `through` emits close when the writable
and readable side of the stream has ended.
If that is not desired, set `autoDestroy=false`.
``` js
var through = require('through')
//like this
var ts = through(write, end, {autoDestroy: false})
//or like this
var ts = through(write, end)
ts.autoDestroy = false
```
## License
MIT / Apache2
var from = require('from')
var through = require('../')
var tape = require('tape')
tape('simple async example', function (t) {
var n = 0, expected = [1,2,3,4,5], actual = []
from(expected)
.pipe(through(function(data) {
this.pause()
n ++
setTimeout(function(){
console.log('pushing data', data)
this.push(data)
this.resume()
}.bind(this), 300)
})).pipe(through(function(data) {
console.log('pushing data second time', data);
this.push(data)
})).on('data', function (d) {
actual.push(d)
}).on('end', function() {
t.deepEqual(actual, expected)
t.end()
})
})
var test = require('tape')
var through = require('../')
// must emit end before close.
test('end before close', function (assert) {
var ts = through()
ts.autoDestroy = false
var ended = false, closed = false
ts.on('end', function () {
assert.ok(!closed)
ended = true
})
ts.on('close', function () {
assert.ok(ended)
closed = true
})
ts.write(1)
ts.write(2)
ts.write(3)
ts.end()
assert.ok(ended)
assert.notOk(closed)
ts.destroy()
assert.ok(closed)
assert.end()
})
var test = require('tape')
var through = require('../')
// must emit end before close.
test('buffering', function(assert) {
var ts = through(function (data) {
this.queue(data)
}, function () {
this.queue(null)
})
var ended = false, actual = []
ts.on('data', actual.push.bind(actual))
ts.on('end', function () {
ended = true
})
ts.write(1)
ts.write(2)
ts.write(3)
assert.deepEqual(actual, [1, 2, 3])
ts.pause()
ts.write(4)
ts.write(5)
ts.write(6)
assert.deepEqual(actual, [1, 2, 3])
ts.resume()
assert.deepEqual(actual, [1, 2, 3, 4, 5, 6])
ts.pause()
ts.end()
assert.ok(!ended)
ts.resume()
assert.ok(ended)
assert.end()
})
test('buffering has data in queue, when ends', function (assert) {
/*
* If stream ends while paused with data in the queue,
* stream should still emit end after all data is written
* on resume.
*/
var ts = through(function (data) {
this.queue(data)
}, function () {
this.queue(null)
})
var ended = false, actual = []
ts.on('data', actual.push.bind(actual))
ts.on('end', function () {
ended = true
})
ts.pause()
ts.write(1)
ts.write(2)
ts.write(3)
ts.end()
assert.deepEqual(actual, [], 'no data written yet, still paused')
assert.ok(!ended, 'end not emitted yet, still paused')
ts.resume()
assert.deepEqual(actual, [1, 2, 3], 'resumed, all data should be delivered')
assert.ok(ended, 'end should be emitted once all data was delivered')
assert.end();
})
var test = require('tape')
var through = require('../')
// must emit end before close.
test('end before close', function (assert) {
var ts = through()
var ended = false, closed = false
ts.on('end', function () {
assert.ok(!closed)
ended = true
})
ts.on('close', function () {
assert.ok(ended)
closed = true
})
ts.write(1)
ts.write(2)
ts.write(3)
ts.end()
assert.ok(ended)
assert.ok(closed)
assert.end()
})
test('end only once', function (t) {
var ts = through()
var ended = false, closed = false
ts.on('end', function () {
t.equal(ended, false)
ended = true
})
ts.queue(null)
ts.queue(null)
ts.queue(null)
ts.resume()
t.end()
})
var test = require('tape')
var spec = require('stream-spec')
var through = require('../')
/*
I'm using these two functions, and not streams and pipe
so there is less to break. if this test fails it must be
the implementation of _through_
*/
function write(array, stream) {
array = array.slice()
function next() {
while(array.length)
if(stream.write(array.shift()) === false)
return stream.once('drain', next)
stream.end()
}
next()
}
function read(stream, callback) {
var actual = []
stream.on('data', function (data) {
actual.push(data)
})
stream.once('end', function () {
callback(null, actual)
})
stream.once('error', function (err) {
callback(err)
})
}
test('simple defaults', function(assert) {
var l = 1000
, expected = []
while(l--) expected.push(l * Math.random())
var t = through()
var s = spec(t).through().pausable()
read(t, function (err, actual) {
assert.ifError(err)
assert.deepEqual(actual, expected)
assert.end()
})
t.on('close', s.validate)
write(expected, t)
});
test('simple functions', function(assert) {
var l = 1000
, expected = []
while(l--) expected.push(l * Math.random())
var t = through(function (data) {
this.emit('data', data*2)
})
var s = spec(t).through().pausable()
read(t, function (err, actual) {
assert.ifError(err)
assert.deepEqual(actual, expected.map(function (data) {
return data*2
}))
assert.end()
})
t.on('close', s.validate)
write(expected, t)
})
test('pauses', function(assert) {
var l = 1000
, expected = []
while(l--) expected.push(l) //Math.random())
var t = through()
var s = spec(t)
.through()
.pausable()
t.on('data', function () {
if(Math.random() > 0.1) return
t.pause()
process.nextTick(function () {
t.resume()
})
})
read(t, function (err, actual) {
assert.ifError(err)
assert.deepEqual(actual, expected)
})
t.on('close', function () {
s.validate()
assert.end()
})
write(expected, t)
})
{
"name": "gm",
"description": "GraphicsMagick and ImageMagick for node.js",
"version": "1.17.0",
"author": {
"name": "Aaron Heckmann",
"email": "aaron.heckmann+github@gmail.com"
},
"keywords": [
"graphics",
"magick",
"image",
"graphicsmagick",
"imagemagick",
"gm",
"convert",
"identify",
"compare"
],
"engines": {
"node": ">= 0.8.0"
},
"bugs": {
"url": "http://github.com/aheckmann/gm/issues"
},
"licenses": [
{
"type": "MIT",
"url": "http://www.opensource.org/licenses/mit-license.php"
}
],
"main": "./index",
"scripts": {
"test": "make test-unit; make test;"
},
"repository": {
"type": "git",
"url": "https://github.com/aheckmann/gm.git"
},
"license": "MIT",
"devDependencies": {
"gleak": "0.4.0",
"async": "~0.2.7"
},
"dependencies": {
"debug": "0.7.0",
"array-series": "~0.1.0",
"array-parallel": "~0.1.0",
"through": "~2.3.1"
},
"gitHead": "2fb65bac7c09ab8b09e87b791b146b82c209076e",
"homepage": "https://github.com/aheckmann/gm",
"_id": "gm@1.17.0",
"_shasum": "27a261e0bdfee3d373d24b5a27bd249057355068",
"_from": "gm@",
"_npmVersion": "1.4.28",
"_npmUser": {
"name": "rwky",
"email": "admin@rwky.net"
},
"maintainers": [
{
"name": "aaron",
"email": "aaron.heckmann+github@gmail.com"
},
{
"name": "jongleberry",
"email": "me@jongleberry.com"
},
{
"name": "rwky",
"email": "admin@rwky.net"
},
{
"name": "fragphace",
"email": "fragphace@gmail.com"
}
],
"dist": {
"shasum": "27a261e0bdfee3d373d24b5a27bd249057355068",
"tarball": "http://registry.npmjs.org/gm/-/gm-1.17.0.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/gm/-/gm-1.17.0.tgz"
}
{
"Records":[
{
"eventVersion":"2.0",
"eventSource":"aws:s3",
"awsRegion":"us-east-1",
"eventTime":"1970-01-01T00:00:00.000Z",
"eventName":"ObjectCreated:Put",
"userIdentity":{
"principalId":"AIDAJDPLRKLG7UEXAMPLE"
},
"requestParameters":{
"sourceIPAddress":"127.0.0.1"
},
"responseElements":{
"x-amz-request-id":"C3D13FE58DE4C810",
"x-amz-id-2":"FMyUVURIY8/IgAtTv8xRjskZQpcIZ9KG4V5Wp6S7S/JRWeUWerMUE5JgHvANOjpD"
},
"s3":{
"s3SchemaVersion":"1.0",
"configurationId":"testConfigRule",
"bucket":{
"name":"sourcebucket",
"ownerIdentity":{
"principalId":"A3NL1KOZZKExample"
},
"arn":"arn:aws:s3:::sourcebucket"
},
"object":{
"key":"HappyFace.jpg",
"size":1024,
"eTag":"d41d8cd98f00b204e9800998ecf8427e",
"versionId":"096fKKXTRTtl3on89fVO.nfljtsv6qko"
}
}
}
]
}
{
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": {
"ExecRole": {
"Type": "AWS::IAM::Role",
"Properties": {
"AssumeRolePolicyDocument": {
"Version" : "2012-10-17",
"Statement": [ {
"Effect": "Allow",
"Principal": {
"Service": [ "lambda.amazonaws.com" ]
},
"Action": [ "sts:AssumeRole" ]
} ]
}
}
},
"ExecRolePolicies": {
"Type": "AWS::IAM::Policy",
"Properties": {
"PolicyName": "ExecRolePolicy",
"PolicyDocument": {
"Version" : "2012-10-17",
"Statement": [ {
"Effect": "Allow",
"Action": [
"logs:*"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": [
"arn:aws:s3:::*"
]
} ]
},
"Roles": [ { "Ref": "ExecRole" } ]
}
},
"InvokeRole": {
"Type": "AWS::IAM::Role",
"Properties": {
"AssumeRolePolicyDocument": {
"Version" : "2012-10-17",
"Statement": [ {
"Effect": "Allow",
"Principal": {
"Service": [ "s3.amazonaws.com" ]
},
"Action": [ "sts:AssumeRole" ],
"Condition": {
"ArnLike": {
"sts:ExternalId": "arn:aws:s3:::*"
}
}
} ]
}
}
},
"InvokeRolePolicies": {
"Type": "AWS::IAM::Policy",
"Properties": {
"PolicyName": "ExecRolePolicy",
"PolicyDocument": {
"Version" : "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Resource": [
"*"
],
"Action": [
"lambda:InvokeFunction"
]
}
]
},
"Roles": [ { "Ref": "InvokeRole" } ]
}
}
}
}