# add dist

This commit is contained in:
Mario Romano
2016-04-21 11:56:31 +01:00
parent 5914688467
commit 07807e7bc3
13499 changed files with 1808930 additions and 5 deletions

View File

@@ -0,0 +1,18 @@
This software is released under the MIT license:
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.

View File

@@ -0,0 +1,233 @@
# readdirp [![Build Status](https://secure.travis-ci.org/thlorenz/readdirp.png)](http://travis-ci.org/thlorenz/readdirp)
[![NPM](https://nodei.co/npm/readdirp.png?downloads=true&stars=true)](https://nodei.co/npm/readdirp/)
Recursive version of [fs.readdir](http://nodejs.org/docs/latest/api/fs.html#fs_fs_readdir_path_callback). Exposes a **stream api**.
```javascript
var readdirp = require('readdirp')
, path = require('path')
, es = require('event-stream');
// print out all JavaScript files along with their size
var stream = readdirp({ root: path.join(__dirname), fileFilter: '*.js' });
stream
.on('warn', function (err) {
console.error('non-fatal error', err);
// optionally call stream.destroy() here in order to abort and cause 'close' to be emitted
})
.on('error', function (err) { console.error('fatal error', err); })
.pipe(es.mapSync(function (entry) {
return { path: entry.path, size: entry.stat.size };
}))
.pipe(es.stringify())
.pipe(process.stdout);
```
Meant to be one of the recursive versions of [fs](http://nodejs.org/docs/latest/api/fs.html) functions, e.g., like [mkdirp](https://github.com/substack/node-mkdirp).
**Table of Contents** *generated with [DocToc](http://doctoc.herokuapp.com/)*
- [Installation](#installation)
- [API](#api)
- [entry stream](#entry-stream)
- [options](#options)
- [entry info](#entry-info)
- [Filters](#filters)
- [Callback API](#callback-api)
- [allProcessed ](#allprocessed)
- [fileProcessed](#fileprocessed)
- [More Examples](#more-examples)
- [stream api](#stream-api)
- [stream api pipe](#stream-api-pipe)
- [grep](#grep)
- [using callback api](#using-callback-api)
- [tests](#tests)
# Installation
npm install readdirp
# API
***var entryStream = readdirp (options)***
Reads given root recursively and returns a `stream` of [entry info](#entry-info)s.
## entry stream
Behaves as follows:
- `emit('data')` passes an [entry info](#entry-info) whenever one is found
- `emit('warn')` passes a non-fatal `Error` that prevents a file/directory from being processed (i.e., if it is
inaccessible to the user)
- `emit('error')` passes a fatal `Error` which also ends the stream (i.e., when illegal options where passed)
- `emit('end')` called when all entries were found and no more will be emitted (i.e., we are done)
- `emit('close')` called when the stream is destroyed via `stream.destroy()` (which could be useful if you want to
manually abort even on a non fatal error) - at that point the stream is no longer `readable` and no more entries,
warning or errors are emitted
- to learn more about streams, consult the very detailed
[nodejs streams documentation](http://nodejs.org/api/stream.html) or the
[stream-handbook](https://github.com/substack/stream-handbook)
## options
- **root**: path in which to start reading and recursing into subdirectories
- **fileFilter**: filter to include/exclude files found (see [Filters](#filters) for more)
- **directoryFilter**: filter to include/exclude directories found and to recurse into (see [Filters](#filters) for more)
- **depth**: depth at which to stop recursing even if more subdirectories are found
- **entryType**: determines if data events on the stream should be emitted for `'files'`, `'directories'`, `'both'`, or `'all'`. Setting to `'all'` will also include entries for other types of file descriptors like character devices, unix sockets and named pipes. Defaults to `'files'`.
- **lstat**: if `true`, readdirp uses `fs.lstat` instead of `fs.stat` in order to stat files and includes symlink entries in the stream along with files.
## entry info
Has the following properties:
- **parentDir** : directory in which entry was found (relative to given root)
- **fullParentDir** : full path to parent directory
- **name** : name of the file/directory
- **path** : path to the file/directory (relative to given root)
- **fullPath** : full path to the file/directory found
- **stat** : built in [stat object](http://nodejs.org/docs/v0.4.9/api/fs.html#fs.Stats)
- **Example**: (assuming root was `/User/dev/readdirp`)
parentDir : 'test/bed/root_dir1',
fullParentDir : '/User/dev/readdirp/test/bed/root_dir1',
name : 'root_dir1_subdir1',
path : 'test/bed/root_dir1/root_dir1_subdir1',
fullPath : '/User/dev/readdirp/test/bed/root_dir1/root_dir1_subdir1',
stat : [ ... ]
## Filters
There are three different ways to specify filters for files and directories respectively.
- **function**: a function that takes an entry info as a parameter and returns true to include or false to exclude the entry
- **glob string**: a string (e.g., `*.js`) which is matched using [minimatch](https://github.com/isaacs/minimatch), so go there for more
information.
Globstars (`**`) are not supported since specifiying a recursive pattern for an already recursive function doesn't make sense.
Negated globs (as explained in the minimatch documentation) are allowed, e.g., `!*.txt` matches everything but text files.
- **array of glob strings**: either need to be all inclusive or all exclusive (negated) patterns otherwise an error is thrown.
`[ '*.json', '*.js' ]` includes all JavaScript and Json files.
`[ '!.git', '!node_modules' ]` includes all directories except the '.git' and 'node_modules'.
Directories that do not pass a filter will not be recursed into.
## Callback API
Although the stream api is recommended, readdirp also exposes a callback based api.
***readdirp (options, callback1 [, callback2])***
If callback2 is given, callback1 functions as the **fileProcessed** callback, and callback2 as the **allProcessed** callback.
If only callback1 is given, it functions as the **allProcessed** callback.
### allProcessed
- function with err and res parameters, e.g., `function (err, res) { ... }`
- **err**: array of errors that occurred during the operation, **res may still be present, even if errors occurred**
- **res**: collection of file/directory [entry infos](#entry-info)
### fileProcessed
- function with [entry info](#entry-info) parameter e.g., `function (entryInfo) { ... }`
# More Examples
`on('error', ..)`, `on('warn', ..)` and `on('end', ..)` handling omitted for brevity
```javascript
var readdirp = require('readdirp');
// Glob file filter
readdirp({ root: './test/bed', fileFilter: '*.js' })
.on('data', function (entry) {
// do something with each JavaScript file entry
});
// Combined glob file filters
readdirp({ root: './test/bed', fileFilter: [ '*.js', '*.json' ] })
.on('data', function (entry) {
// do something with each JavaScript and Json file entry
});
// Combined negated directory filters
readdirp({ root: './test/bed', directoryFilter: [ '!.git', '!*modules' ] })
.on('data', function (entry) {
// do something with each file entry found outside '.git' or any modules directory
});
// Function directory filter
readdirp({ root: './test/bed', directoryFilter: function (di) { return di.name.length === 9; } })
.on('data', function (entry) {
// do something with each file entry found inside directories whose name has length 9
});
// Limiting depth
readdirp({ root: './test/bed', depth: 1 })
.on('data', function (entry) {
// do something with each file entry found up to 1 subdirectory deep
});
// callback api
readdirp(
{ root: '.' }
, function(fileInfo) {
// do something with file entry here
}
, function (err, res) {
// all done, move on or do final step for all file entries here
}
);
```
Try more examples by following [instructions](https://github.com/thlorenz/readdirp/blob/master/examples/Readme.md)
on how to get going.
## stream api
[stream-api.js](https://github.com/thlorenz/readdirp/blob/master/examples/stream-api.js)
Demonstrates error and data handling by listening to events emitted from the readdirp stream.
## stream api pipe
[stream-api-pipe.js](https://github.com/thlorenz/readdirp/blob/master/examples/stream-api-pipe.js)
Demonstrates error handling by listening to events emitted from the readdirp stream and how to pipe the data stream into
another destination stream.
## grep
[grep.js](https://github.com/thlorenz/readdirp/blob/master/examples/grep.js)
Very naive implementation of grep, for demonstration purposes only.
## using callback api
[callback-api.js](https://github.com/thlorenz/readdirp/blob/master/examples/callback-api.js)
Shows how to pass callbacks in order to handle errors and/or data.
## tests
The [readdirp tests](https://github.com/thlorenz/readdirp/blob/master/test/readdirp.js) also will give you a good idea on
how things work.

View File

@@ -0,0 +1,37 @@
# readdirp examples
## How to run the examples
Assuming you installed readdirp (`npm install readdirp`), you can do the following:
1. `npm explore readdirp`
2. `cd examples`
3. `npm install`
At that point you can run the examples with node, i.e., `node grep`.
## stream api
[stream-api.js](https://github.com/thlorenz/readdirp/blob/master/examples/stream-api.js)
Demonstrates error and data handling by listening to events emitted from the readdirp stream.
## stream api pipe
[stream-api-pipe.js](https://github.com/thlorenz/readdirp/blob/master/examples/stream-api-pipe.js)
Demonstrates error handling by listening to events emitted from the readdirp stream and how to pipe the data stream into
another destination stream.
## grep
[grep.js](https://github.com/thlorenz/readdirp/blob/master/examples/grep.js)
Very naive implementation of grep, for demonstration purposes only.
## using callback api
[callback-api.js](https://github.com/thlorenz/readdirp/blob/master/examples/callback-api.js)
Shows how to pass callbacks in order to handle errors and/or data.

View File

@@ -0,0 +1,10 @@
var readdirp = require('..');
readdirp({ root: '.', fileFilter: '*.js' }, function (errors, res) {
if (errors) {
errors.forEach(function (err) {
console.error('Error: ', err);
});
}
console.log('all javascript files', res);
});

View File

@@ -0,0 +1,71 @@
'use strict';
var readdirp = require('..')
, util = require('util')
, fs = require('fs')
, path = require('path')
, es = require('event-stream')
;
function findLinesMatching (searchTerm) {
return es.through(function (entry) {
var lineno = 0
, matchingLines = []
, fileStream = this;
function filter () {
return es.mapSync(function (line) {
lineno++;
return ~line.indexOf(searchTerm) ? lineno + ': ' + line : undefined;
});
}
function aggregate () {
return es.through(
function write (data) {
matchingLines.push(data);
}
, function end () {
// drop files that had no matches
if (matchingLines.length) {
var result = { file: entry, lines: matchingLines };
// pass result on to file stream
fileStream.emit('data', result);
}
this.emit('end');
}
);
}
fs.createReadStream(entry.fullPath, { encoding: 'utf-8' })
// handle file contents line by line
.pipe(es.split('\n'))
// keep only the lines that matched the term
.pipe(filter())
// aggregate all matching lines and delegate control back to the file stream
.pipe(aggregate())
;
});
}
console.log('grepping for "arguments"');
// create a stream of all javascript files found in this and all sub directories
readdirp({ root: path.join(__dirname), fileFilter: '*.js' })
// find all lines matching the term for each file (if none found, that file is ignored)
.pipe(findLinesMatching('arguments'))
// format the results and output
.pipe(
es.mapSync(function (res) {
return '\n\n' + res.file.path + '\n\t' + res.lines.join('\n\t');
})
)
.pipe(process.stdout)
;

View File

@@ -0,0 +1,9 @@
{
"name": "readdirp-examples",
"version": "0.0.0",
"description": "Examples for readdirp.",
"dependencies": {
"tap-stream": "~0.1.0",
"event-stream": "~3.0.7"
}
}

View File

@@ -0,0 +1,19 @@
var readdirp = require('..')
, path = require('path')
, through = require('through2')
// print out all JavaScript files along with their size
readdirp({ root: path.join(__dirname), fileFilter: '*.js' })
.on('warn', function (err) { console.error('non-fatal error', err); })
.on('error', function (err) { console.error('fatal error', err); })
.pipe(through.obj(function (entry, _, cb) {
this.push({ path: entry.path, size: entry.stat.size });
cb();
}))
.pipe(through.obj(
function (res, _, cb) {
this.push(JSON.stringify(res) + '\n');
cb();
})
)
.pipe(process.stdout);

View File

@@ -0,0 +1,15 @@
var readdirp = require('..')
, path = require('path');
readdirp({ root: path.join(__dirname), fileFilter: '*.js' })
.on('warn', function (err) {
console.error('something went wrong when processing an entry', err);
})
.on('error', function (err) {
console.error('something went fatally wrong and the stream was aborted', err);
})
.on('data', function (entry) {
console.log('%s is ready for processing', entry.path);
// process entry here
});

View File

@@ -0,0 +1,19 @@
Copyright Node.js contributors. All rights reserved.
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.

View File

@@ -0,0 +1,3 @@
# core-util-is
The `util.is*` functions introduced in Node v0.12.

View File

@@ -0,0 +1,604 @@
diff --git a/lib/util.js b/lib/util.js
index a03e874..9074e8e 100644
--- a/lib/util.js
+++ b/lib/util.js
@@ -19,430 +19,6 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
-var formatRegExp = /%[sdj%]/g;
-exports.format = function(f) {
- if (!isString(f)) {
- var objects = [];
- for (var i = 0; i < arguments.length; i++) {
- objects.push(inspect(arguments[i]));
- }
- return objects.join(' ');
- }
-
- var i = 1;
- var args = arguments;
- var len = args.length;
- var str = String(f).replace(formatRegExp, function(x) {
- if (x === '%%') return '%';
- if (i >= len) return x;
- switch (x) {
- case '%s': return String(args[i++]);
- case '%d': return Number(args[i++]);
- case '%j':
- try {
- return JSON.stringify(args[i++]);
- } catch (_) {
- return '[Circular]';
- }
- default:
- return x;
- }
- });
- for (var x = args[i]; i < len; x = args[++i]) {
- if (isNull(x) || !isObject(x)) {
- str += ' ' + x;
- } else {
- str += ' ' + inspect(x);
- }
- }
- return str;
-};
-
-
-// Mark that a method should not be used.
-// Returns a modified function which warns once by default.
-// If --no-deprecation is set, then it is a no-op.
-exports.deprecate = function(fn, msg) {
- // Allow for deprecating things in the process of starting up.
- if (isUndefined(global.process)) {
- return function() {
- return exports.deprecate(fn, msg).apply(this, arguments);
- };
- }
-
- if (process.noDeprecation === true) {
- return fn;
- }
-
- var warned = false;
- function deprecated() {
- if (!warned) {
- if (process.throwDeprecation) {
- throw new Error(msg);
- } else if (process.traceDeprecation) {
- console.trace(msg);
- } else {
- console.error(msg);
- }
- warned = true;
- }
- return fn.apply(this, arguments);
- }
-
- return deprecated;
-};
-
-
-var debugs = {};
-var debugEnviron;
-exports.debuglog = function(set) {
- if (isUndefined(debugEnviron))
- debugEnviron = process.env.NODE_DEBUG || '';
- set = set.toUpperCase();
- if (!debugs[set]) {
- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
- var pid = process.pid;
- debugs[set] = function() {
- var msg = exports.format.apply(exports, arguments);
- console.error('%s %d: %s', set, pid, msg);
- };
- } else {
- debugs[set] = function() {};
- }
- }
- return debugs[set];
-};
-
-
-/**
- * Echos the value of a value. Trys to print the value out
- * in the best way possible given the different types.
- *
- * @param {Object} obj The object to print out.
- * @param {Object} opts Optional options object that alters the output.
- */
-/* legacy: obj, showHidden, depth, colors*/
-function inspect(obj, opts) {
- // default options
- var ctx = {
- seen: [],
- stylize: stylizeNoColor
- };
- // legacy...
- if (arguments.length >= 3) ctx.depth = arguments[2];
- if (arguments.length >= 4) ctx.colors = arguments[3];
- if (isBoolean(opts)) {
- // legacy...
- ctx.showHidden = opts;
- } else if (opts) {
- // got an "options" object
- exports._extend(ctx, opts);
- }
- // set default options
- if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
- if (isUndefined(ctx.depth)) ctx.depth = 2;
- if (isUndefined(ctx.colors)) ctx.colors = false;
- if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
- if (ctx.colors) ctx.stylize = stylizeWithColor;
- return formatValue(ctx, obj, ctx.depth);
-}
-exports.inspect = inspect;
-
-
-// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
-inspect.colors = {
- 'bold' : [1, 22],
- 'italic' : [3, 23],
- 'underline' : [4, 24],
- 'inverse' : [7, 27],
- 'white' : [37, 39],
- 'grey' : [90, 39],
- 'black' : [30, 39],
- 'blue' : [34, 39],
- 'cyan' : [36, 39],
- 'green' : [32, 39],
- 'magenta' : [35, 39],
- 'red' : [31, 39],
- 'yellow' : [33, 39]
-};
-
-// Don't use 'blue' not visible on cmd.exe
-inspect.styles = {
- 'special': 'cyan',
- 'number': 'yellow',
- 'boolean': 'yellow',
- 'undefined': 'grey',
- 'null': 'bold',
- 'string': 'green',
- 'date': 'magenta',
- // "name": intentionally not styling
- 'regexp': 'red'
-};
-
-
-function stylizeWithColor(str, styleType) {
- var style = inspect.styles[styleType];
-
- if (style) {
- return '\u001b[' + inspect.colors[style][0] + 'm' + str +
- '\u001b[' + inspect.colors[style][1] + 'm';
- } else {
- return str;
- }
-}
-
-
-function stylizeNoColor(str, styleType) {
- return str;
-}
-
-
-function arrayToHash(array) {
- var hash = {};
-
- array.forEach(function(val, idx) {
- hash[val] = true;
- });
-
- return hash;
-}
-
-
-function formatValue(ctx, value, recurseTimes) {
- // Provide a hook for user-specified inspect functions.
- // Check that value is an object with an inspect function on it
- if (ctx.customInspect &&
- value &&
- isFunction(value.inspect) &&
- // Filter out the util module, it's inspect function is special
- value.inspect !== exports.inspect &&
- // Also filter out any prototype objects using the circular check.
- !(value.constructor && value.constructor.prototype === value)) {
- var ret = value.inspect(recurseTimes, ctx);
- if (!isString(ret)) {
- ret = formatValue(ctx, ret, recurseTimes);
- }
- return ret;
- }
-
- // Primitive types cannot have properties
- var primitive = formatPrimitive(ctx, value);
- if (primitive) {
- return primitive;
- }
-
- // Look up the keys of the object.
- var keys = Object.keys(value);
- var visibleKeys = arrayToHash(keys);
-
- if (ctx.showHidden) {
- keys = Object.getOwnPropertyNames(value);
- }
-
- // Some type of object without properties can be shortcutted.
- if (keys.length === 0) {
- if (isFunction(value)) {
- var name = value.name ? ': ' + value.name : '';
- return ctx.stylize('[Function' + name + ']', 'special');
- }
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- }
- if (isDate(value)) {
- return ctx.stylize(Date.prototype.toString.call(value), 'date');
- }
- if (isError(value)) {
- return formatError(value);
- }
- }
-
- var base = '', array = false, braces = ['{', '}'];
-
- // Make Array say that they are Array
- if (isArray(value)) {
- array = true;
- braces = ['[', ']'];
- }
-
- // Make functions say that they are functions
- if (isFunction(value)) {
- var n = value.name ? ': ' + value.name : '';
- base = ' [Function' + n + ']';
- }
-
- // Make RegExps say that they are RegExps
- if (isRegExp(value)) {
- base = ' ' + RegExp.prototype.toString.call(value);
- }
-
- // Make dates with properties first say the date
- if (isDate(value)) {
- base = ' ' + Date.prototype.toUTCString.call(value);
- }
-
- // Make error with message first say the error
- if (isError(value)) {
- base = ' ' + formatError(value);
- }
-
- if (keys.length === 0 && (!array || value.length == 0)) {
- return braces[0] + base + braces[1];
- }
-
- if (recurseTimes < 0) {
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- } else {
- return ctx.stylize('[Object]', 'special');
- }
- }
-
- ctx.seen.push(value);
-
- var output;
- if (array) {
- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
- } else {
- output = keys.map(function(key) {
- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
- });
- }
-
- ctx.seen.pop();
-
- return reduceToSingleString(output, base, braces);
-}
-
-
-function formatPrimitive(ctx, value) {
- if (isUndefined(value))
- return ctx.stylize('undefined', 'undefined');
- if (isString(value)) {
- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
- .replace(/'/g, "\\'")
- .replace(/\\"/g, '"') + '\'';
- return ctx.stylize(simple, 'string');
- }
- if (isNumber(value)) {
- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0,
- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 .
- if (value === 0 && 1 / value < 0)
- return ctx.stylize('-0', 'number');
- return ctx.stylize('' + value, 'number');
- }
- if (isBoolean(value))
- return ctx.stylize('' + value, 'boolean');
- // For some reason typeof null is "object", so special case here.
- if (isNull(value))
- return ctx.stylize('null', 'null');
-}
-
-
-function formatError(value) {
- return '[' + Error.prototype.toString.call(value) + ']';
-}
-
-
-function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
- var output = [];
- for (var i = 0, l = value.length; i < l; ++i) {
- if (hasOwnProperty(value, String(i))) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- String(i), true));
- } else {
- output.push('');
- }
- }
- keys.forEach(function(key) {
- if (!key.match(/^\d+$/)) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- key, true));
- }
- });
- return output;
-}
-
-
-function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
- var name, str, desc;
- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
- if (desc.get) {
- if (desc.set) {
- str = ctx.stylize('[Getter/Setter]', 'special');
- } else {
- str = ctx.stylize('[Getter]', 'special');
- }
- } else {
- if (desc.set) {
- str = ctx.stylize('[Setter]', 'special');
- }
- }
- if (!hasOwnProperty(visibleKeys, key)) {
- name = '[' + key + ']';
- }
- if (!str) {
- if (ctx.seen.indexOf(desc.value) < 0) {
- if (isNull(recurseTimes)) {
- str = formatValue(ctx, desc.value, null);
- } else {
- str = formatValue(ctx, desc.value, recurseTimes - 1);
- }
- if (str.indexOf('\n') > -1) {
- if (array) {
- str = str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n').substr(2);
- } else {
- str = '\n' + str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n');
- }
- }
- } else {
- str = ctx.stylize('[Circular]', 'special');
- }
- }
- if (isUndefined(name)) {
- if (array && key.match(/^\d+$/)) {
- return str;
- }
- name = JSON.stringify('' + key);
- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
- name = name.substr(1, name.length - 2);
- name = ctx.stylize(name, 'name');
- } else {
- name = name.replace(/'/g, "\\'")
- .replace(/\\"/g, '"')
- .replace(/(^"|"$)/g, "'");
- name = ctx.stylize(name, 'string');
- }
- }
-
- return name + ': ' + str;
-}
-
-
-function reduceToSingleString(output, base, braces) {
- var numLinesEst = 0;
- var length = output.reduce(function(prev, cur) {
- numLinesEst++;
- if (cur.indexOf('\n') >= 0) numLinesEst++;
- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
- }, 0);
-
- if (length > 60) {
- return braces[0] +
- (base === '' ? '' : base + '\n ') +
- ' ' +
- output.join(',\n ') +
- ' ' +
- braces[1];
- }
-
- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
-}
-
-
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
@@ -522,166 +98,10 @@ function isPrimitive(arg) {
exports.isPrimitive = isPrimitive;
function isBuffer(arg) {
- return arg instanceof Buffer;
+ return Buffer.isBuffer(arg);
}
exports.isBuffer = isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
-}
-
-
-function pad(n) {
- return n < 10 ? '0' + n.toString(10) : n.toString(10);
-}
-
-
-var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
- 'Oct', 'Nov', 'Dec'];
-
-// 26 Feb 16:19:34
-function timestamp() {
- var d = new Date();
- var time = [pad(d.getHours()),
- pad(d.getMinutes()),
- pad(d.getSeconds())].join(':');
- return [d.getDate(), months[d.getMonth()], time].join(' ');
-}
-
-
-// log is just a thin wrapper to console.log that prepends a timestamp
-exports.log = function() {
- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
-};
-
-
-/**
- * Inherit the prototype methods from one constructor into another.
- *
- * The Function.prototype.inherits from lang.js rewritten as a standalone
- * function (not on Function.prototype). NOTE: If this file is to be loaded
- * during bootstrapping this function needs to be rewritten using some native
- * functions as prototype setup using normal JavaScript does not work as
- * expected during bootstrapping (see mirror.js in r114903).
- *
- * @param {function} ctor Constructor function which needs to inherit the
- * prototype.
- * @param {function} superCtor Constructor function to inherit prototype from.
- */
-exports.inherits = function(ctor, superCtor) {
- ctor.super_ = superCtor;
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
-};
-
-exports._extend = function(origin, add) {
- // Don't do anything if add isn't an object
- if (!add || !isObject(add)) return origin;
-
- var keys = Object.keys(add);
- var i = keys.length;
- while (i--) {
- origin[keys[i]] = add[keys[i]];
- }
- return origin;
-};
-
-function hasOwnProperty(obj, prop) {
- return Object.prototype.hasOwnProperty.call(obj, prop);
-}
-
-
-// Deprecated old stuff.
-
-exports.p = exports.deprecate(function() {
- for (var i = 0, len = arguments.length; i < len; ++i) {
- console.error(exports.inspect(arguments[i]));
- }
-}, 'util.p: Use console.error() instead');
-
-
-exports.exec = exports.deprecate(function() {
- return require('child_process').exec.apply(this, arguments);
-}, 'util.exec is now called `child_process.exec`.');
-
-
-exports.print = exports.deprecate(function() {
- for (var i = 0, len = arguments.length; i < len; ++i) {
- process.stdout.write(String(arguments[i]));
- }
-}, 'util.print: Use console.log instead');
-
-
-exports.puts = exports.deprecate(function() {
- for (var i = 0, len = arguments.length; i < len; ++i) {
- process.stdout.write(arguments[i] + '\n');
- }
-}, 'util.puts: Use console.log instead');
-
-
-exports.debug = exports.deprecate(function(x) {
- process.stderr.write('DEBUG: ' + x + '\n');
-}, 'util.debug: Use console.error instead');
-
-
-exports.error = exports.deprecate(function(x) {
- for (var i = 0, len = arguments.length; i < len; ++i) {
- process.stderr.write(arguments[i] + '\n');
- }
-}, 'util.error: Use console.error instead');
-
-
-exports.pump = exports.deprecate(function(readStream, writeStream, callback) {
- var callbackCalled = false;
-
- function call(a, b, c) {
- if (callback && !callbackCalled) {
- callback(a, b, c);
- callbackCalled = true;
- }
- }
-
- readStream.addListener('data', function(chunk) {
- if (writeStream.write(chunk) === false) readStream.pause();
- });
-
- writeStream.addListener('drain', function() {
- readStream.resume();
- });
-
- readStream.addListener('end', function() {
- writeStream.end();
- });
-
- readStream.addListener('close', function() {
- call();
- });
-
- readStream.addListener('error', function(err) {
- writeStream.end();
- call(err);
- });
-
- writeStream.addListener('error', function(err) {
- readStream.destroy();
- call(err);
- });
-}, 'util.pump(): Use readableStream.pipe() instead');
-
-
-var uv;
-exports._errnoException = function(err, syscall) {
- if (isUndefined(uv)) uv = process.binding('uv');
- var errname = uv.errname(err);
- var e = new Error(syscall + ' ' + errname);
- e.code = errname;
- e.errno = errname;
- e.syscall = syscall;
- return e;
-};
+}

View File

@@ -0,0 +1,86 @@
{
"_args": [
[
"core-util-is@~1.0.0",
"/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/readdirp/node_modules/readable-stream"
]
],
"_from": "core-util-is@>=1.0.0 <1.1.0",
"_id": "core-util-is@1.0.2",
"_inCache": true,
"_installable": true,
"_location": "/readdirp/core-util-is",
"_nodeVersion": "4.0.0",
"_npmUser": {
"email": "i@izs.me",
"name": "isaacs"
},
"_npmVersion": "3.3.2",
"_phantomChildren": {},
"_requested": {
"name": "core-util-is",
"raw": "core-util-is@~1.0.0",
"rawSpec": "~1.0.0",
"scope": null,
"spec": ">=1.0.0 <1.1.0",
"type": "range"
},
"_requiredBy": [
"/readdirp/readable-stream"
],
"_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",
"_shasum": "b5fd54220aa2bc5ab57aab7140c940754503c1a7",
"_shrinkwrap": null,
"_spec": "core-util-is@~1.0.0",
"_where": "/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/readdirp/node_modules/readable-stream",
"author": {
"email": "i@izs.me",
"name": "Isaac Z. Schlueter",
"url": "http://blog.izs.me/"
},
"bugs": {
"url": "https://github.com/isaacs/core-util-is/issues"
},
"dependencies": {},
"description": "The `util.is*` functions introduced in Node v0.12.",
"devDependencies": {
"tap": "^2.3.0"
},
"directories": {},
"dist": {
"shasum": "b5fd54220aa2bc5ab57aab7140c940754503c1a7",
"tarball": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz"
},
"gitHead": "a177da234df5638b363ddc15fa324619a38577c8",
"homepage": "https://github.com/isaacs/core-util-is#readme",
"keywords": [
"util",
"isBuffer",
"isArray",
"isNumber",
"isString",
"isRegExp",
"isThis",
"isThat",
"polyfill"
],
"license": "MIT",
"main": "lib/util.js",
"maintainers": [
{
"email": "i@izs.me",
"name": "isaacs"
}
],
"name": "core-util-is",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/isaacs/core-util-is.git"
},
"scripts": {
"test": "tap test.js"
},
"version": "1.0.2"
}

View File

@@ -0,0 +1,68 @@
var assert = require('tap');
var t = require('./lib/util');
assert.equal(t.isArray([]), true);
assert.equal(t.isArray({}), false);
assert.equal(t.isBoolean(null), false);
assert.equal(t.isBoolean(true), true);
assert.equal(t.isBoolean(false), true);
assert.equal(t.isNull(null), true);
assert.equal(t.isNull(undefined), false);
assert.equal(t.isNull(false), false);
assert.equal(t.isNull(), false);
assert.equal(t.isNullOrUndefined(null), true);
assert.equal(t.isNullOrUndefined(undefined), true);
assert.equal(t.isNullOrUndefined(false), false);
assert.equal(t.isNullOrUndefined(), true);
assert.equal(t.isNumber(null), false);
assert.equal(t.isNumber('1'), false);
assert.equal(t.isNumber(1), true);
assert.equal(t.isString(null), false);
assert.equal(t.isString('1'), true);
assert.equal(t.isString(1), false);
assert.equal(t.isSymbol(null), false);
assert.equal(t.isSymbol('1'), false);
assert.equal(t.isSymbol(1), false);
assert.equal(t.isSymbol(Symbol()), true);
assert.equal(t.isUndefined(null), false);
assert.equal(t.isUndefined(undefined), true);
assert.equal(t.isUndefined(false), false);
assert.equal(t.isUndefined(), true);
assert.equal(t.isRegExp(null), false);
assert.equal(t.isRegExp('1'), false);
assert.equal(t.isRegExp(new RegExp()), true);
assert.equal(t.isObject({}), true);
assert.equal(t.isObject([]), true);
assert.equal(t.isObject(new RegExp()), true);
assert.equal(t.isObject(new Date()), true);
assert.equal(t.isDate(null), false);
assert.equal(t.isDate('1'), false);
assert.equal(t.isDate(new Date()), true);
assert.equal(t.isError(null), false);
assert.equal(t.isError({ err: true }), false);
assert.equal(t.isError(new Error()), true);
assert.equal(t.isFunction(null), false);
assert.equal(t.isFunction({ }), false);
assert.equal(t.isFunction(function() {}), true);
assert.equal(t.isPrimitive(null), true);
assert.equal(t.isPrimitive(''), true);
assert.equal(t.isPrimitive(0), true);
assert.equal(t.isPrimitive(new Date()), false);
assert.equal(t.isBuffer(null), false);
assert.equal(t.isBuffer({}), false);
assert.equal(t.isBuffer(new Buffer(0)), true);

View File

@@ -0,0 +1,6 @@
test:
@node_modules/.bin/tape test.js
.PHONY: test

View File

@@ -0,0 +1,60 @@
# isarray
`Array#isArray` for older browsers.
[![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray)
[![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray)
[![browser support](https://ci.testling.com/juliangruber/isarray.png)
](https://ci.testling.com/juliangruber/isarray)
## Usage
```js
var isArray = require('isarray');
console.log(isArray([])); // => true
console.log(isArray({})); // => false
```
## Installation
With [npm](http://npmjs.org) do
```bash
$ npm install isarray
```
Then bundle for the browser with
[browserify](https://github.com/substack/browserify).
With [component](http://component.io) do
```bash
$ component install juliangruber/isarray
```
## License
(MIT)
Copyright (c) 2013 Julian Gruber &lt;julian@juliangruber.com&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.

View File

@@ -0,0 +1,19 @@
{
"name" : "isarray",
"description" : "Array#isArray for older browsers",
"version" : "0.0.1",
"repository" : "juliangruber/isarray",
"homepage": "https://github.com/juliangruber/isarray",
"main" : "index.js",
"scripts" : [
"index.js"
],
"dependencies" : {},
"keywords": ["browser","isarray","array"],
"author": {
"name": "Julian Gruber",
"email": "mail@juliangruber.com",
"url": "http://juliangruber.com"
},
"license": "MIT"
}

View File

@@ -0,0 +1,5 @@
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};

View File

@@ -0,0 +1,96 @@
{
"_args": [
[
"isarray@~1.0.0",
"/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/readdirp/node_modules/readable-stream"
]
],
"_from": "isarray@>=1.0.0 <1.1.0",
"_id": "isarray@1.0.0",
"_inCache": true,
"_installable": true,
"_location": "/readdirp/isarray",
"_nodeVersion": "5.1.0",
"_npmUser": {
"email": "julian@juliangruber.com",
"name": "juliangruber"
},
"_npmVersion": "3.3.12",
"_phantomChildren": {},
"_requested": {
"name": "isarray",
"raw": "isarray@~1.0.0",
"rawSpec": "~1.0.0",
"scope": null,
"spec": ">=1.0.0 <1.1.0",
"type": "range"
},
"_requiredBy": [
"/readdirp/readable-stream"
],
"_resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
"_shasum": "bb935d48582cba168c06834957a54a3e07124f11",
"_shrinkwrap": null,
"_spec": "isarray@~1.0.0",
"_where": "/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/readdirp/node_modules/readable-stream",
"author": {
"email": "mail@juliangruber.com",
"name": "Julian Gruber",
"url": "http://juliangruber.com"
},
"bugs": {
"url": "https://github.com/juliangruber/isarray/issues"
},
"dependencies": {},
"description": "Array#isArray for older browsers",
"devDependencies": {
"tape": "~2.13.4"
},
"directories": {},
"dist": {
"shasum": "bb935d48582cba168c06834957a54a3e07124f11",
"tarball": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz"
},
"gitHead": "2a23a281f369e9ae06394c0fb4d2381355a6ba33",
"homepage": "https://github.com/juliangruber/isarray",
"keywords": [
"browser",
"isarray",
"array"
],
"license": "MIT",
"main": "index.js",
"maintainers": [
{
"email": "julian@juliangruber.com",
"name": "juliangruber"
}
],
"name": "isarray",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/juliangruber/isarray.git"
},
"scripts": {
"test": "tape test.js"
},
"testling": {
"browsers": [
"ie/8..latest",
"firefox/17..latest",
"firefox/nightly",
"chrome/22..latest",
"chrome/canary",
"opera/12..latest",
"opera/next",
"safari/5.1..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2..latest"
],
"files": "test.js"
},
"version": "1.0.0"
}

View File

@@ -0,0 +1,20 @@
var isArray = require('./');
var test = require('tape');
test('is array', function(t){
t.ok(isArray([]));
t.notOk(isArray({}));
t.notOk(isArray(null));
t.notOk(isArray(false));
var obj = {};
obj[0] = true;
t.notOk(isArray(obj));
var arr = [];
arr.foo = 'bar';
t.ok(isArray(arr));
t.end();
});

View File

@@ -0,0 +1,18 @@
Copyright Joyent, Inc. and other Node contributors. All rights reserved.
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.

View File

@@ -0,0 +1,36 @@
# readable-stream
***Node-core v5.9.1 streams for userland*** [![Build Status](https://travis-ci.org/nodejs/readable-stream.svg?branch=master)](https://travis-ci.org/nodejs/readable-stream)
[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/)
[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/)
[![Sauce Test Status](https://saucelabs.com/browser-matrix/readable-stream.svg)](https://saucelabs.com/u/readable-stream)
```bash
npm install --save readable-stream
```
***Node-core streams for userland***
This package is a mirror of the Streams2 and Streams3 implementations in
Node-core, including [documentation](doc/stream.markdown).
If you want to guarantee a stable streams base, regardless of what version of
Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html).
As of version 2.0.0 **readable-stream** uses semantic versioning.
# Streams WG Team Members
* **Chris Dickinson** ([@chrisdickinson](https://github.com/chrisdickinson)) &lt;christopher.s.dickinson@gmail.com&gt;
- Release GPG key: 9554F04D7259F04124DE6B476D5A82AC7E37093B
* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) &lt;calvin.metcalf@gmail.com&gt;
- Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242
* **Rod Vagg** ([@rvagg](https://github.com/rvagg)) &lt;rod@vagg.org&gt;
- Release GPG key: DD8F2338BAE7501E3DD5AC78C273792F7D83545D
* **Sam Newman** ([@sonewman](https://github.com/sonewman)) &lt;newmansam@outlook.com&gt;
* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) &lt;mathiasbuus@gmail.com&gt;
* **Domenic Denicola** ([@domenic](https://github.com/domenic)) &lt;d@domenic.me&gt;

View File

@@ -0,0 +1,60 @@
# streams WG Meeting 2015-01-30
## Links
* **Google Hangouts Video**: http://www.youtube.com/watch?v=I9nDOSGfwZg
* **GitHub Issue**: https://github.com/iojs/readable-stream/issues/106
* **Original Minutes Google Doc**: https://docs.google.com/document/d/17aTgLnjMXIrfjgNaTUnHQO7m3xgzHR2VXBTmi03Qii4/
## Agenda
Extracted from https://github.com/iojs/readable-stream/labels/wg-agenda prior to meeting.
* adopt a charter [#105](https://github.com/iojs/readable-stream/issues/105)
* release and versioning strategy [#101](https://github.com/iojs/readable-stream/issues/101)
* simpler stream creation [#102](https://github.com/iojs/readable-stream/issues/102)
* proposal: deprecate implicit flowing of streams [#99](https://github.com/iojs/readable-stream/issues/99)
## Minutes
### adopt a charter
* group: +1's all around
### What versioning scheme should be adopted?
* group: +1s 3.0.0
* domenic+group: pulling in patches from other sources where appropriate
* mikeal: version independently, suggesting versions for io.js
* mikeal+domenic: work with TC to notify in advance of changes
simpler stream creation
### streamline creation of streams
* sam: streamline creation of streams
* domenic: nice simple solution posted
but, we lose the opportunity to change the model
may not be backwards incompatible (double check keys)
**action item:** domenic will check
### remove implicit flowing of streams on(data)
* add isFlowing / isPaused
* mikeal: worrying that were documenting polyfill methods confuses users
* domenic: more reflective API is probably good, with warning labels for users
* new section for mad scientists (reflective stream access)
* calvin: name the “third state”
* mikeal: maybe borrow the name from whatwg?
* domenic: were missing the “third state”
* consensus: kind of difficult to name the third state
* mikeal: figure out differences in states / compat
* mathias: always flow on data eliminates third state
* explore what it breaks
**action items:**
* ask isaac for ability to list packages by what public io.js APIs they use (esp. Stream)
* ask rod/build for infrastructure
* **chris**: explore the “flow on data” approach
* add isPaused/isFlowing
* add new docs section
* move isPaused to that section

View File

@@ -0,0 +1 @@
module.exports = require("./lib/_stream_duplex.js")

View File

@@ -0,0 +1,122 @@
{
"_args": [
[
"readable-stream@^2.0.2",
"/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/readdirp"
]
],
"_from": "readable-stream@>=2.0.2 <3.0.0",
"_id": "readable-stream@2.1.0",
"_inCache": true,
"_installable": true,
"_location": "/readdirp/readable-stream",
"_nodeVersion": "5.10.1",
"_npmOperationalInternal": {
"host": "packages-16-east.internal.npmjs.com",
"tmp": "tmp/readable-stream-2.1.0.tgz_1460568003255_0.9190005895216018"
},
"_npmUser": {
"email": "calvin.metcalf@gmail.com",
"name": "cwmma"
},
"_npmVersion": "3.8.3",
"_phantomChildren": {},
"_requested": {
"name": "readable-stream",
"raw": "readable-stream@^2.0.2",
"rawSpec": "^2.0.2",
"scope": null,
"spec": ">=2.0.2 <3.0.0",
"type": "range"
},
"_requiredBy": [
"/readdirp"
],
"_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.1.0.tgz",
"_shasum": "36f42ea0424eb29a985e4a81d31be2f96e1f2f80",
"_shrinkwrap": null,
"_spec": "readable-stream@^2.0.2",
"_where": "/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/readdirp",
"browser": {
"util": false
},
"browserify": {
"transform": [
"inline-process-browser",
"unreachable-branch-transform"
]
},
"bugs": {
"url": "https://github.com/nodejs/readable-stream/issues"
},
"dependencies": {
"core-util-is": "~1.0.0",
"inherits": "~2.0.1",
"inline-process-browser": "~2.0.1",
"isarray": "~1.0.0",
"process-nextick-args": "~1.0.6",
"string_decoder": "~0.10.x",
"unreachable-branch-transform": "~0.5.0",
"util-deprecate": "~1.0.1"
},
"description": "Streams3, a user-land copy of the stream library from Node.js",
"devDependencies": {
"nyc": "^6.4.0",
"tap": "~0.7.1",
"tape": "~4.5.1",
"zuul": "~3.9.0"
},
"directories": {},
"dist": {
"shasum": "36f42ea0424eb29a985e4a81d31be2f96e1f2f80",
"tarball": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.1.0.tgz"
},
"gitHead": "4c2d8e2639ffd516b12544ce0c117cc0345daa3f",
"homepage": "https://github.com/nodejs/readable-stream#readme",
"keywords": [
"readable",
"stream",
"pipe"
],
"license": "MIT",
"main": "readable.js",
"maintainers": [
{
"email": "isaacs@npmjs.com",
"name": "isaacs"
},
{
"email": "nathan@tootallnate.net",
"name": "tootallnate"
},
{
"email": "rod@vagg.org",
"name": "rvagg"
},
{
"email": "calvin.metcalf@gmail.com",
"name": "cwmma"
}
],
"name": "readable-stream",
"nyc": {
"include": [
"lib/**.js"
]
},
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/nodejs/readable-stream.git"
},
"scripts": {
"browser": "npm run write-zuul && zuul -- test/browser.js",
"cover": "nyc npm test",
"local": "zuul --local -- test/browser.js",
"report": "nyc report --reporter=lcov",
"test": "tap test/parallel/*.js test/ours/*.js",
"write-zuul": "printf \"ui: tape\nbrowsers:\n - name: $BROWSER_NAME\n version: $BROWSER_VERSION\n\">.zuul.yml"
},
"version": "2.1.0"
}

View File

@@ -0,0 +1 @@
module.exports = require("./lib/_stream_passthrough.js")

View File

@@ -0,0 +1,18 @@
var Stream = (function (){
try {
return require('st' + 'ream'); // hack to fix a circular dependency issue when used with browserify
} catch(_){}
}());
exports = module.exports = require('./lib/_stream_readable.js');
exports.Stream = Stream || exports;
exports.Readable = exports;
exports.Writable = require('./lib/_stream_writable.js');
exports.Duplex = require('./lib/_stream_duplex.js');
exports.Transform = require('./lib/_stream_transform.js');
exports.PassThrough = require('./lib/_stream_passthrough.js');
// inline-process-browser and unreachable-branch-transform make sure this is
// removed in browserify builds
if (!process.browser && process.env.READABLE_STREAM === 'disable') {
module.exports = require('stream');
}

View File

@@ -0,0 +1 @@
module.exports = require("./lib/_stream_transform.js")

View File

@@ -0,0 +1 @@
module.exports = require("./lib/_stream_writable.js")

View File

@@ -0,0 +1,106 @@
{
"_args": [
[
"readdirp@^2.0.0",
"/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/browser-sync/node_modules/chokidar"
]
],
"_from": "readdirp@>=2.0.0 <3.0.0",
"_id": "readdirp@2.0.0",
"_inCache": true,
"_installable": true,
"_location": "/readdirp",
"_npmUser": {
"email": "thlorenz@gmx.de",
"name": "thlorenz"
},
"_npmVersion": "1.4.28",
"_phantomChildren": {
"inherits": "2.0.1",
"inline-process-browser": "2.0.1",
"process-nextick-args": "1.0.6",
"string_decoder": "0.10.31",
"unreachable-branch-transform": "0.5.1",
"util-deprecate": "1.0.2"
},
"_requested": {
"name": "readdirp",
"raw": "readdirp@^2.0.0",
"rawSpec": "^2.0.0",
"scope": null,
"spec": ">=2.0.0 <3.0.0",
"type": "range"
},
"_requiredBy": [
"/browser-sync/chokidar"
],
"_resolved": "https://registry.npmjs.org/readdirp/-/readdirp-2.0.0.tgz",
"_shasum": "cc09ba5d12d8feb864bc75f6e2ebc137060cbd82",
"_shrinkwrap": null,
"_spec": "readdirp@^2.0.0",
"_where": "/Users/mromano/dev/dev-platform-webcomponents/ng2-components/ng2-alfresco-documentslist/node_modules/browser-sync/node_modules/chokidar",
"author": {
"email": "thlorenz@gmx.de",
"name": "Thorsten Lorenz",
"url": "thlorenz.com"
},
"bugs": {
"url": "https://github.com/thlorenz/readdirp/issues"
},
"dependencies": {
"graceful-fs": "^4.1.2",
"minimatch": "^2.0.10",
"readable-stream": "^2.0.2"
},
"description": "Recursive version of fs.readdir with streaming api.",
"devDependencies": {
"nave": "^0.5.1",
"tap": "^1.3.2",
"through2": "^2.0.0"
},
"directories": {},
"dist": {
"shasum": "cc09ba5d12d8feb864bc75f6e2ebc137060cbd82",
"tarball": "https://registry.npmjs.org/readdirp/-/readdirp-2.0.0.tgz"
},
"engines": {
"node": ">=0.6"
},
"gitHead": "480af1e35d413ebb36e427808dcaa65d47cdc490",
"homepage": "https://github.com/thlorenz/readdirp",
"keywords": [
"recursive",
"fs",
"stream",
"streams",
"readdir",
"filesystem",
"find",
"filter"
],
"license": "MIT",
"main": "readdirp.js",
"maintainers": [
{
"email": "thlorenz@gmx.de",
"name": "thlorenz"
}
],
"name": "readdirp",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/thlorenz/readdirp.git"
},
"scripts": {
"test": "if [ -e $TRAVIS ]; then npm run test-all; else npm run test-main; fi",
"test-0.10": "nave use 0.10 npm run test-main",
"test-0.12": "nave use 0.12 npm run test-main",
"test-0.8": "nave use 0.8 npm run test-main",
"test-2.4": "nave use 2.4 npm run test-main",
"test-all": "npm run test-main && npm run test-0.8 && npm run test-0.10 && npm run test-0.12 && npm run test-2.4",
"test-main": "(cd test && set -e; for t in ./*.js; do node $t; done)"
},
"version": "2.0.0"
}

View File

@@ -0,0 +1,288 @@
'use strict';
var fs = require('graceful-fs')
, path = require('path')
, minimatch = require('minimatch')
, toString = Object.prototype.toString
;
// Standard helpers
function isFunction (obj) {
return toString.call(obj) === '[object Function]';
}
function isString (obj) {
return toString.call(obj) === '[object String]';
}
function isRegExp (obj) {
return toString.call(obj) === '[object RegExp]';
}
function isUndefined (obj) {
return obj === void 0;
}
/**
* Main function which ends up calling readdirRec and reads all files and directories in given root recursively.
* @param { Object } opts Options to specify root (start directory), filters and recursion depth
* @param { function } callback1 When callback2 is given calls back for each processed file - function (fileInfo) { ... },
* when callback2 is not given, it behaves like explained in callback2
* @param { function } callback2 Calls back once all files have been processed with an array of errors and file infos
* function (err, fileInfos) { ... }
*/
function readdir(opts, callback1, callback2) {
var stream
, handleError
, handleFatalError
, pending = 0
, errors = []
, readdirResult = {
directories: []
, files: []
}
, fileProcessed
, allProcessed
, realRoot
, aborted = false
;
// If no callbacks were given we will use a streaming interface
if (isUndefined(callback1)) {
var api = require('./stream-api')();
stream = api.stream;
callback1 = api.processEntry;
callback2 = api.done;
handleError = api.handleError;
handleFatalError = api.handleFatalError;
stream.on('close', function () { aborted = true; });
} else {
handleError = function (err) { errors.push(err); };
handleFatalError = function (err) {
handleError(err);
allProcessed(errors, null);
};
}
if (isUndefined(opts)){
handleFatalError(new Error (
'Need to pass at least one argument: opts! \n' +
'https://github.com/thlorenz/readdirp#options'
)
);
return stream;
}
opts.root = opts.root || '.';
opts.fileFilter = opts.fileFilter || function() { return true; };
opts.directoryFilter = opts.directoryFilter || function() { return true; };
opts.depth = typeof opts.depth === 'undefined' ? 999999999 : opts.depth;
opts.entryType = opts.entryType || 'files';
var statfn = opts.lstat === true ? fs.lstat.bind(fs) : fs.stat.bind(fs);
if (isUndefined(callback2)) {
fileProcessed = function() { };
allProcessed = callback1;
} else {
fileProcessed = callback1;
allProcessed = callback2;
}
function normalizeFilter (filter) {
if (isUndefined(filter)) return undefined;
function isNegated (filters) {
function negated(f) {
return f.indexOf('!') === 0;
}
var some = filters.some(negated);
if (!some) {
return false;
} else {
if (filters.every(negated)) {
return true;
} else {
// if we detect illegal filters, bail out immediately
throw new Error(
'Cannot mix negated with non negated glob filters: ' + filters + '\n' +
'https://github.com/thlorenz/readdirp#filters'
);
}
}
}
// Turn all filters into a function
if (isFunction(filter)) {
return filter;
} else if (isString(filter)) {
return function (entryInfo) {
return minimatch(entryInfo.name, filter.trim());
};
} else if (filter && Array.isArray(filter)) {
if (filter) filter = filter.map(function (f) {
return f.trim();
});
return isNegated(filter) ?
// use AND to concat multiple negated filters
function (entryInfo) {
return filter.every(function (f) {
return minimatch(entryInfo.name, f);
});
}
:
// use OR to concat multiple inclusive filters
function (entryInfo) {
return filter.some(function (f) {
return minimatch(entryInfo.name, f);
});
};
}
}
function processDir(currentDir, entries, callProcessed) {
if (aborted) return;
var total = entries.length
, processed = 0
, entryInfos = []
;
fs.realpath(currentDir, function(err, realCurrentDir) {
if (aborted) return;
if (err) {
handleError(err);
callProcessed(entryInfos);
return;
}
var relDir = path.relative(realRoot, realCurrentDir);
if (entries.length === 0) {
callProcessed([]);
} else {
entries.forEach(function (entry) {
var fullPath = path.join(realCurrentDir, entry)
, relPath = path.join(relDir, entry);
statfn(fullPath, function (err, stat) {
if (err) {
handleError(err);
} else {
entryInfos.push({
name : entry
, path : relPath // relative to root
, fullPath : fullPath
, parentDir : relDir // relative to root
, fullParentDir : realCurrentDir
, stat : stat
});
}
processed++;
if (processed === total) callProcessed(entryInfos);
});
});
}
});
}
function readdirRec(currentDir, depth, callCurrentDirProcessed) {
if (aborted) return;
fs.readdir(currentDir, function (err, entries) {
if (err) {
handleError(err);
callCurrentDirProcessed();
return;
}
processDir(currentDir, entries, function(entryInfos) {
var subdirs = entryInfos
.filter(function (ei) { return ei.stat.isDirectory() && opts.directoryFilter(ei); });
subdirs.forEach(function (di) {
if(opts.entryType === 'directories' || opts.entryType === 'both' || opts.entryType === 'all') {
fileProcessed(di);
}
readdirResult.directories.push(di);
});
entryInfos
.filter(function(ei) {
var isCorrectType = opts.entryType === 'all' ?
!ei.stat.isDirectory() : ei.stat.isFile() || ei.stat.isSymbolicLink();
return isCorrectType && opts.fileFilter(ei);
})
.forEach(function (fi) {
if(opts.entryType === 'files' || opts.entryType === 'both' || opts.entryType === 'all') {
fileProcessed(fi);
}
readdirResult.files.push(fi);
});
var pendingSubdirs = subdirs.length;
// Be done if no more subfolders exist or we reached the maximum desired depth
if(pendingSubdirs === 0 || depth === opts.depth) {
callCurrentDirProcessed();
} else {
// recurse into subdirs, keeping track of which ones are done
// and call back once all are processed
subdirs.forEach(function (subdir) {
readdirRec(subdir.fullPath, depth + 1, function () {
pendingSubdirs = pendingSubdirs - 1;
if(pendingSubdirs === 0) {
callCurrentDirProcessed();
}
});
});
}
});
});
}
// Validate and normalize filters
try {
opts.fileFilter = normalizeFilter(opts.fileFilter);
opts.directoryFilter = normalizeFilter(opts.directoryFilter);
} catch (err) {
// if we detect illegal filters, bail out immediately
handleFatalError(err);
return stream;
}
// If filters were valid get on with the show
fs.realpath(opts.root, function(err, res) {
if (err) {
handleFatalError(err);
return stream;
}
realRoot = res;
readdirRec(opts.root, 0, function () {
// All errors are collected into the errors array
if (errors.length > 0) {
allProcessed(errors, readdirResult);
} else {
allProcessed(null, readdirResult);
}
});
});
return stream;
}
module.exports = readdir;

View File

@@ -0,0 +1,100 @@
'use strict';
var si = typeof setImmediate !== 'undefined' ? setImmediate : function (fn) { setTimeout(fn, 0) };
var stream = require('readable-stream');
var util = require('util');
var Readable = stream.Readable;
module.exports = ReaddirpReadable;
util.inherits(ReaddirpReadable, Readable);
function ReaddirpReadable (opts) {
if (!(this instanceof ReaddirpReadable)) return new ReaddirpReadable(opts);
opts = opts || {};
opts.objectMode = true;
Readable.call(this, opts);
// backpressure not implemented at this point
this.highWaterMark = Infinity;
this._destroyed = false;
this._paused = false;
this._warnings = [];
this._errors = [];
this._pauseResumeErrors();
}
var proto = ReaddirpReadable.prototype;
proto._pauseResumeErrors = function () {
var self = this;
self.on('pause', function () { self._paused = true });
self.on('resume', function () {
if (self._destroyed) return;
self._paused = false;
self._warnings.forEach(function (err) { self.emit('warn', err) });
self._warnings.length = 0;
self._errors.forEach(function (err) { self.emit('error', err) });
self._errors.length = 0;
})
}
// called for each entry
proto._processEntry = function (entry) {
if (this._destroyed) return;
this.push(entry);
}
proto._read = function () { }
proto.destroy = function () {
// when stream is destroyed it will emit nothing further, not even errors or warnings
this.push(null);
this.readable = false;
this._destroyed = true;
this.emit('close');
}
proto._done = function () {
this.push(null);
}
// we emit errors and warnings async since we may handle errors like invalid args
// within the initial event loop before any event listeners subscribed
proto._handleError = function (err) {
var self = this;
si(function () {
if (self._paused) return self._warnings.push(err);
if (!self._destroyed) self.emit('warn', err);
});
}
proto._handleFatalError = function (err) {
var self = this;
si(function () {
if (self._paused) return self._errors.push(err);
if (!self._destroyed) self.emit('error', err);
});
}
function createStreamAPI () {
var stream = new ReaddirpReadable();
return {
stream : stream
, processEntry : stream._processEntry.bind(stream)
, done : stream._done.bind(stream)
, handleError : stream._handleError.bind(stream)
, handleFatalError : stream._handleFatalError.bind(stream)
};
}
module.exports = createStreamAPI;

View File

@@ -0,0 +1,310 @@
/*jshint asi:true */
var debug //= true;
var test = debug ? function () {} : require('tap').test
var test_ = !debug ? function () {} : require('tap').test
, path = require('path')
, fs = require('fs')
, util = require('util')
, TransformStream = require('readable-stream').Transform
, through = require('through2')
, streamapi = require('../stream-api')
, readdirp = require('..')
, root = path.join(__dirname, 'bed')
, totalDirs = 6
, totalFiles = 12
, ext1Files = 4
, ext2Files = 3
, ext3Files = 2
;
// see test/readdirp.js for test bed layout
function opts (extend) {
var o = { root: root };
if (extend) {
for (var prop in extend) {
o[prop] = extend[prop];
}
}
return o;
}
function capture () {
var result = { entries: [], errors: [], ended: false }
, dst = new TransformStream({ objectMode: true });
dst._transform = function (entry, _, cb) {
result.entries.push(entry);
cb();
}
dst._flush = function (cb) {
result.ended = true;
this.push(result);
cb();
}
return dst;
}
test('\nintegrated', function (t) {
t.test('\n# reading root without filter', function (t) {
t.plan(2);
readdirp(opts())
.on('error', function (err) {
t.fail('should not throw error', err);
})
.pipe(capture())
.pipe(through.obj(
function (result, _ , cb) {
t.equals(result.entries.length, totalFiles, 'emits all files');
t.ok(result.ended, 'ends stream');
t.end();
cb();
}
));
})
t.test('\n# normal: ["*.ext1", "*.ext3"]', function (t) {
t.plan(2);
readdirp(opts( { fileFilter: [ '*.ext1', '*.ext3' ] } ))
.on('error', function (err) {
t.fail('should not throw error', err);
})
.pipe(capture())
.pipe(through.obj(
function (result, _ , cb) {
t.equals(result.entries.length, ext1Files + ext3Files, 'all ext1 and ext3 files');
t.ok(result.ended, 'ends stream');
t.end();
cb();
}
))
})
t.test('\n# files only', function (t) {
t.plan(2);
readdirp(opts( { entryType: 'files' } ))
.on('error', function (err) {
t.fail('should not throw error', err);
})
.pipe(capture())
.pipe(through.obj(
function (result, _ , cb) {
t.equals(result.entries.length, totalFiles, 'returned files');
t.ok(result.ended, 'ends stream');
t.end();
cb();
}
))
})
t.test('\n# directories only', function (t) {
t.plan(2);
readdirp(opts( { entryType: 'directories' } ))
.on('error', function (err) {
t.fail('should not throw error', err);
})
.pipe(capture())
.pipe(through.obj(
function (result, _ , cb) {
t.equals(result.entries.length, totalDirs, 'returned directories');
t.ok(result.ended, 'ends stream');
t.end();
cb();
}
))
})
t.test('\n# both directories + files', function (t) {
t.plan(2);
readdirp(opts( { entryType: 'both' } ))
.on('error', function (err) {
t.fail('should not throw error', err);
})
.pipe(capture())
.pipe(through.obj(
function (result, _ , cb) {
t.equals(result.entries.length, totalDirs + totalFiles, 'returned everything');
t.ok(result.ended, 'ends stream');
t.end();
cb();
}
))
})
t.test('\n# directory filter with directories only', function (t) {
t.plan(2);
readdirp(opts( { entryType: 'directories', directoryFilter: [ 'root_dir1', '*dir1_subdir1' ] } ))
.on('error', function (err) {
t.fail('should not throw error', err);
})
.pipe(capture())
.pipe(through.obj(
function (result, _ , cb) {
t.equals(result.entries.length, 2, 'two directories');
t.ok(result.ended, 'ends stream');
t.end();
cb();
}
))
})
t.test('\n# directory and file filters with both entries', function (t) {
t.plan(2);
readdirp(opts( { entryType: 'both', directoryFilter: [ 'root_dir1', '*dir1_subdir1' ], fileFilter: [ '!*.ext1' ] } ))
.on('error', function (err) {
t.fail('should not throw error', err);
})
.pipe(capture())
.pipe(through.obj(
function (result, _ , cb) {
t.equals(result.entries.length, 6, '2 directories and 4 files');
t.ok(result.ended, 'ends stream');
t.end();
cb();
}
))
})
t.test('\n# negated: ["!*.ext1", "!*.ext3"]', function (t) {
t.plan(2);
readdirp(opts( { fileFilter: [ '!*.ext1', '!*.ext3' ] } ))
.on('error', function (err) {
t.fail('should not throw error', err);
})
.pipe(capture())
.pipe(through.obj(
function (result, _ , cb) {
t.equals(result.entries.length, totalFiles - ext1Files - ext3Files, 'all but ext1 and ext3 files');
t.ok(result.ended, 'ends stream');
t.end();
}
))
})
t.test('\n# no options given', function (t) {
t.plan(1);
readdirp()
.on('error', function (err) {
t.similar(err.toString() , /Need to pass at least one argument/ , 'emits meaningful error');
t.end();
})
})
t.test('\n# mixed: ["*.ext1", "!*.ext3"]', function (t) {
t.plan(1);
readdirp(opts( { fileFilter: [ '*.ext1', '!*.ext3' ] } ))
.on('error', function (err) {
t.similar(err.toString() , /Cannot mix negated with non negated glob filters/ , 'emits meaningful error');
t.end();
})
})
})
test('\napi separately', function (t) {
t.test('\n# handleError', function (t) {
t.plan(1);
var api = streamapi()
, warning = new Error('some file caused problems');
api.stream
.on('warn', function (err) {
t.equals(err, warning, 'warns with the handled error');
})
api.handleError(warning);
})
t.test('\n# when stream is paused and then resumed', function (t) {
t.plan(6);
var api = streamapi()
, resumed = false
, fatalError = new Error('fatal!')
, nonfatalError = new Error('nonfatal!')
, processedData = 'some data'
;
api.stream
.on('warn', function (err) {
t.equals(err, nonfatalError, 'emits the buffered warning');
t.ok(resumed, 'emits warning only after it was resumed');
})
.on('error', function (err) {
t.equals(err, fatalError, 'emits the buffered fatal error');
t.ok(resumed, 'emits errors only after it was resumed');
})
.on('data', function (data) {
t.equals(data, processedData, 'emits the buffered data');
t.ok(resumed, 'emits data only after it was resumed');
})
.pause()
api.processEntry(processedData);
api.handleError(nonfatalError);
api.handleFatalError(fatalError);
setTimeout(function () {
resumed = true;
api.stream.resume();
}, 1)
})
t.test('\n# when a stream is destroyed, it emits "closed", but no longer emits "data", "warn" and "error"', function (t) {
var api = streamapi()
, fatalError = new Error('fatal!')
, nonfatalError = new Error('nonfatal!')
, processedData = 'some data'
, plan = 0;
t.plan(6)
var stream = api.stream
.on('warn', function (err) {
t.ok(!stream._destroyed, 'emits warning until destroyed');
})
.on('error', function (err) {
t.ok(!stream._destroyed, 'emits errors until destroyed');
})
.on('data', function (data) {
t.ok(!stream._destroyed, 'emits data until destroyed');
})
.on('close', function () {
t.ok(stream._destroyed, 'emits close when stream is destroyed');
})
api.processEntry(processedData);
api.handleError(nonfatalError);
api.handleFatalError(fatalError);
setTimeout(function () {
stream.destroy()
t.notOk(stream.readable, 'stream is no longer readable after it is destroyed')
api.processEntry(processedData);
api.handleError(nonfatalError);
api.handleFatalError(fatalError);
process.nextTick(function () {
t.pass('emits no more data, warn or error events after it was destroyed')
t.end();
})
}, 10)
})
})

View File

@@ -0,0 +1,289 @@
/*jshint asi:true */
var test = require('tap').test
, path = require('path')
, fs = require('fs')
, util = require('util')
, net = require('net')
, readdirp = require('../readdirp.js')
, root = path.join(__dirname, '../test/bed')
, totalDirs = 6
, totalFiles = 12
, ext1Files = 4
, ext2Files = 3
, ext3Files = 2
, rootDir2Files = 2
, nameHasLength9Dirs = 2
, depth1Files = 8
, depth0Files = 3
;
/*
Structure of test bed:
.
├── root_dir1
│   ├── root_dir1_file1.ext1
│   ├── root_dir1_file2.ext2
│   ├── root_dir1_file3.ext3
│   ├── root_dir1_subdir1
│   │   └── root1_dir1_subdir1_file1.ext1
│   └── root_dir1_subdir2
│   └── .gitignore
├── root_dir2
│   ├── root_dir2_file1.ext1
│   ├── root_dir2_file2.ext2
│   ├── root_dir2_subdir1
│   │   └── .gitignore
│   └── root_dir2_subdir2
│   └── .gitignore
├── root_file1.ext1
├── root_file2.ext2
└── root_file3.ext3
6 directories, 13 files
*/
// console.log('\033[2J'); // clear console
function opts (extend) {
var o = { root: root };
if (extend) {
for (var prop in extend) {
o[prop] = extend[prop];
}
}
return o;
}
test('\nreading root without filter', function (t) {
t.plan(2);
readdirp(opts(), function (err, res) {
t.equals(res.directories.length, totalDirs, 'all directories');
t.equals(res.files.length, totalFiles, 'all files');
t.end();
})
})
test('\nreading root without filter using lstat', function (t) {
t.plan(2);
readdirp(opts({ lstat: true }), function (err, res) {
t.equals(res.directories.length, totalDirs, 'all directories');
t.equals(res.files.length, totalFiles, 'all files');
t.end();
})
})
test('\nreading root with symlinks using lstat', function (t) {
t.plan(2);
fs.symlinkSync(path.join(root, 'root_dir1'), path.join(root, 'dirlink'));
fs.symlinkSync(path.join(root, 'root_file1.ext1'), path.join(root, 'link.ext1'));
readdirp(opts({ lstat: true }), function (err, res) {
t.equals(res.directories.length, totalDirs, 'all directories');
t.equals(res.files.length, totalFiles + 2, 'all files + symlinks');
fs.unlinkSync(path.join(root, 'dirlink'));
fs.unlinkSync(path.join(root, 'link.ext1'));
t.end();
})
})
test('\nreading non-standard fds', function (t) {
t.plan(2);
var server = net.createServer().listen(path.join(root, 'test.sock'), function(){
readdirp(opts({ entryType: 'all' }), function (err, res) {
t.equals(res.files.length, totalFiles + 1, 'all files + socket');
readdirp(opts({ entryType: 'both' }), function (err, res) {
t.equals(res.files.length, totalFiles, 'all regular files only');
server.close();
t.end();
})
})
});
})
test('\nreading root using glob filter', function (t) {
// normal
t.test('\n# "*.ext1"', function (t) {
t.plan(1);
readdirp(opts( { fileFilter: '*.ext1' } ), function (err, res) {
t.equals(res.files.length, ext1Files, 'all ext1 files');
t.end();
})
})
t.test('\n# ["*.ext1", "*.ext3"]', function (t) {
t.plan(1);
readdirp(opts( { fileFilter: [ '*.ext1', '*.ext3' ] } ), function (err, res) {
t.equals(res.files.length, ext1Files + ext3Files, 'all ext1 and ext3 files');
t.end();
})
})
t.test('\n# "root_dir1"', function (t) {
t.plan(1);
readdirp(opts( { directoryFilter: 'root_dir1' }), function (err, res) {
t.equals(res.directories.length, 1, 'one directory');
t.end();
})
})
t.test('\n# ["root_dir1", "*dir1_subdir1"]', function (t) {
t.plan(1);
readdirp(opts( { directoryFilter: [ 'root_dir1', '*dir1_subdir1' ]}), function (err, res) {
t.equals(res.directories.length, 2, 'two directories');
t.end();
})
})
t.test('\n# negated: "!*.ext1"', function (t) {
t.plan(1);
readdirp(opts( { fileFilter: '!*.ext1' } ), function (err, res) {
t.equals(res.files.length, totalFiles - ext1Files, 'all but ext1 files');
t.end();
})
})
t.test('\n# negated: ["!*.ext1", "!*.ext3"]', function (t) {
t.plan(1);
readdirp(opts( { fileFilter: [ '!*.ext1', '!*.ext3' ] } ), function (err, res) {
t.equals(res.files.length, totalFiles - ext1Files - ext3Files, 'all but ext1 and ext3 files');
t.end();
})
})
t.test('\n# mixed: ["*.ext1", "!*.ext3"]', function (t) {
t.plan(1);
readdirp(opts( { fileFilter: [ '*.ext1', '!*.ext3' ] } ), function (err, res) {
t.similar(err[0].toString(), /Cannot mix negated with non negated glob filters/, 'returns meaningfull error');
t.end();
})
})
t.test('\n# leading and trailing spaces: [" *.ext1", "*.ext3 "]', function (t) {
t.plan(1);
readdirp(opts( { fileFilter: [ ' *.ext1', '*.ext3 ' ] } ), function (err, res) {
t.equals(res.files.length, ext1Files + ext3Files, 'all ext1 and ext3 files');
t.end();
})
})
t.test('\n# leading and trailing spaces: [" !*.ext1", " !*.ext3 "]', function (t) {
t.plan(1);
readdirp(opts( { fileFilter: [ ' !*.ext1', ' !*.ext3' ] } ), function (err, res) {
t.equals(res.files.length, totalFiles - ext1Files - ext3Files, 'all but ext1 and ext3 files');
t.end();
})
})
t.test('\n# ** glob pattern', function (t) {
t.plan(1);
readdirp(opts( { fileFilter: '**/*.ext1' } ), function (err, res) {
t.equals(res.files.length, ext1Files, 'ignores ** in **/*.ext1 -> only *.ext1 files');
t.end();
})
})
})
test('\n\nreading root using function filter', function (t) {
t.test('\n# file filter -> "contains root_dir2"', function (t) {
t.plan(1);
readdirp(
opts( { fileFilter: function (fi) { return fi.name.indexOf('root_dir2') >= 0; } })
, function (err, res) {
t.equals(res.files.length, rootDir2Files, 'all rootDir2Files');
t.end();
}
)
})
t.test('\n# directory filter -> "name has length 9"', function (t) {
t.plan(1);
readdirp(
opts( { directoryFilter: function (di) { return di.name.length === 9; } })
, function (err, res) {
t.equals(res.directories.length, nameHasLength9Dirs, 'all all dirs with name length 9');
t.end();
}
)
})
})
test('\nreading root specifying maximum depth', function (t) {
t.test('\n# depth 1', function (t) {
t.plan(1);
readdirp(opts( { depth: 1 } ), function (err, res) {
t.equals(res.files.length, depth1Files, 'does not return files at depth 2');
})
})
})
test('\nreading root with no recursion', function (t) {
t.test('\n# depth 0', function (t) {
t.plan(1);
readdirp(opts( { depth: 0 } ), function (err, res) {
t.equals(res.files.length, depth0Files, 'does not return files at depth 0');
})
})
})
test('\nprogress callbacks', function (t) {
t.plan(2);
var pluckName = function(fi) { return fi.name; }
, processedFiles = [];
readdirp(
opts()
, function(fi) {
processedFiles.push(fi);
}
, function (err, res) {
t.equals(processedFiles.length, res.files.length, 'calls back for each file processed');
t.deepEquals(processedFiles.map(pluckName).sort(),res.files.map(pluckName).sort(), 'same file names');
t.end();
}
)
})
test('resolving of name, full and relative paths', function (t) {
var expected = {
name : 'root_dir1_file1.ext1'
, parentDirName : 'root_dir1'
, path : 'root_dir1/root_dir1_file1.ext1'
, fullPath : 'test/bed/root_dir1/root_dir1_file1.ext1'
}
, opts = [
{ root: './bed' , prefix: '' }
, { root: './bed/' , prefix: '' }
, { root: 'bed' , prefix: '' }
, { root: 'bed/' , prefix: '' }
, { root: '../test/bed/' , prefix: '' }
, { root: '.' , prefix: 'bed' }
]
t.plan(opts.length);
opts.forEach(function (op) {
op.fileFilter = 'root_dir1_file1.ext1';
t.test('\n' + util.inspect(op), function (t) {
t.plan(4);
readdirp (op, function(err, res) {
t.equals(res.files[0].name, expected.name, 'correct name');
t.equals(res.files[0].path, path.join(op.prefix, expected.path), 'correct path');
})
fs.realpath(op.root, function(err, fullRoot) {
readdirp (op, function(err, res) {
t.equals(
res.files[0].fullParentDir
, path.join(fullRoot, op.prefix, expected.parentDirName)
, 'correct parentDir'
);
t.equals(
res.files[0].fullPath
, path.join(fullRoot, op.prefix, expected.parentDirName, expected.name)
, 'correct fullPath'
);
})
})
})
})
})