Commit 0dbf42fd authored by Alexandra Rogova's avatar Alexandra Rogova

added 2 hour timeout

parent 6a876f89
......@@ -27,6 +27,11 @@ function runScriptSync(list, callback) {
var err = code === 0 ? null : new Error('exit code ' + code);
callback(err);
});
setTimeout(() => {
stream.write(items + ",Timeout error" + "\n");
process.kill();
return;
}, 7200000); //2 hours
}
fs.truncateSync("./results/add_csv_attachments.csv");
......
......@@ -27,6 +27,11 @@ function runScriptSync(list, callback) {
var err = code === 0 ? null : new Error('exit code ' + code);
callback(err);
});
setTimeout(() => {
stream.write(items + ",Timeout error" + "\n");
process.kill();
return;
}, 7200000); //2 hours
}
fs.truncateSync("./results/add_csv_metadata.csv");
......
......@@ -57,10 +57,10 @@ function init_server (){
console.log(msg);
var ramAfter = (os.totalmem() - os.freemem()) / 1024 / 1024;
var ramUsed = ramAfter - ramBefore;
//console.log("Ram used : " + ramUsed + " MB");
console.log("Ram used : " + ramUsed + " MB");
si.mem(function(data){
process.send(ramUsed + "," + -(data.used / 1024 / 1024 - memBefore));
//console.log("Memory used : " + (data.used / 1024 / 1024 - memBefore) + " MB");
//process.send(ramUsed + "," + -(data.used / 1024 / 1024 - memBefore));
console.log("Memory used : " + (data.used / 1024 / 1024 - memBefore) + " MB");
});
browser.close();
});
......
var childProcess = require('child_process');
const execa = require('execa');
const fs = require('fs');
var stream = fs.createWriteStream("./results/add_random_csv_attachment.csv", {flags:'a'});
......@@ -27,6 +28,12 @@ function runScriptSync(list, callback) {
var err = code === 0 ? null : new Error('exit code ' + code);
callback(err);
});
setTimeout(() => {
stream.write(items + ",Timeout error" + "\n");
process.kill();
return;
}, 7200000); //2 hours
}
fs.truncateSync("./results/add_random_csv_attachment.csv");
......
......@@ -27,6 +27,11 @@ function runScriptSync(list, callback) {
var err = code === 0 ? null : new Error('exit code ' + code);
callback(err);
});
setTimeout(() => {
stream.write(items + ",Timeout error" + "\n");
process.kill();
return;
}, 7200000); //2 hours
}
fs.truncateSync("./results/add_random_csv_metadata.csv");
......
......@@ -27,6 +27,11 @@ function runScriptSync(list, callback) {
var err = code === 0 ? null : new Error('exit code ' + code);
callback(err);
});
setTimeout(() => {
stream.write(items + ",Timeout error" + "\n");
process.kill();
return;
}, 7200000); //2 hours
}
fs.truncateSync("./results/content_csv_size.csv");
......
......@@ -27,6 +27,11 @@ function runScriptSync(list, callback) {
var err = code === 0 ? null : new Error('exit code ' + code);
callback(err);
});
setTimeout(() => {
stream.write(items + ",Timeout error" + "\n");
process.kill();
return;
}, 7200000); //2 hours
}
fs.truncateSync("./results/content_random_size.csv");
......
......@@ -27,6 +27,11 @@ function runScriptSync(list, callback) {
var err = code === 0 ? null : new Error('exit code ' + code);
callback(err);
});
setTimeout(() => {
stream.write(items + ",Timeout error" + "\n");
process.kill();
return;
}, 7200000); //2 hours
}
fs.truncateSync("./results/index_csv_size.csv");
......
......@@ -27,6 +27,11 @@ function runScriptSync(list, callback) {
var err = code === 0 ? null : new Error('exit code ' + code);
callback(err);
});
setTimeout(() => {
stream.write(items + ",Timeout error" + "\n");
process.kill();
return;
}, 7200000); //2 hours
}
fs.truncateSync("./results/index_random_size.csv");
......
......@@ -27,6 +27,11 @@ function runScriptSync(list, callback) {
var err = code === 0 ? null : new Error('exit code ' + code);
callback(err);
});
setTimeout(() => {
stream.write(items + ",Timeout error" + "\n");
process.kill();
return;
}, 7200000); //2 hours
}
fs.truncateSync("./results/export_content.csv");
......
......@@ -27,6 +27,11 @@ function runScriptSync(list, callback) {
var err = code === 0 ? null : new Error('exit code ' + code);
callback(err);
});
setTimeout(() => {
stream.write(items + ",Timeout error" + "\n");
process.kill();
return;
}, 7200000); //2 hours
}
fs.truncateSync("./results/export_index.csv");
......
......@@ -27,6 +27,11 @@ function runScriptSync(list, callback) {
var err = code === 0 ? null : new Error('exit code ' + code);
callback(err);
});
setTimeout(() => {
stream.write(items + ",Timeout error" + "\n");
process.kill();
return;
}, 7200000); //2 hours
}
fs.truncateSync("./results/import_content.csv");
......
......@@ -27,6 +27,11 @@ function runScriptSync(list, callback) {
var err = code === 0 ? null : new Error('exit code ' + code);
callback(err);
});
setTimeout(() => {
stream.write(items + ",Timeout error" + "\n");
process.kill();
return;
}, 7200000); //2 hours
}
fs.truncateSync("./results/import_content_bulk.csv");
......
......@@ -27,6 +27,11 @@ function runScriptSync(list, callback) {
var err = code === 0 ? null : new Error('exit code ' + code);
callback(err);
});
setTimeout(() => {
stream.write(items + ",Timeout error" + "\n");
process.kill();
return;
}, 7200000); //2 hours
}
fs.truncateSync("./results/import_content_uncompressed.csv");
......
......@@ -27,6 +27,11 @@ function runScriptSync(list, callback) {
var err = code === 0 ? null : new Error('exit code ' + code);
callback(err);
});
setTimeout(() => {
stream.write(items + ",Timeout error" + "\n");
process.kill();
return;
}, 7200000); //2 hours
}
fs.truncateSync("./results/import_index.csv");
......
......@@ -27,6 +27,11 @@ function runScriptSync(list, callback) {
var err = code === 0 ? null : new Error('exit code ' + code);
callback(err);
});
setTimeout(() => {
stream.write(items + ",Timeout error" + "\n");
process.kill();
return;
}, 7200000); //2 hours
}
fs.truncateSync("./results/import_index_uncompressed.csv");
......
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../which/bin/node-which" "$@"
ret=$?
else
node "$basedir/../which/bin/node-which" "$@"
ret=$?
fi
exit $ret
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\which\bin\node-which" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\which\bin\node-which" %*
)
\ No newline at end of file
# Changelog
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
### [7.0.1](https://github.com/moxystudio/node-cross-spawn/compare/v7.0.0...v7.0.1) (2019-10-07)
### Bug Fixes
* **core:** support worker threads ([#127](https://github.com/moxystudio/node-cross-spawn/issues/127)) ([cfd49c9](https://github.com/moxystudio/node-cross-spawn/commit/cfd49c9))
## [7.0.0](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.5...v7.0.0) (2019-09-03)
### ⚠ BREAKING CHANGES
* drop support for Node.js < 8
* drop support for versions below Node.js 8 ([#125](https://github.com/moxystudio/node-cross-spawn/issues/125)) ([16feb53](https://github.com/moxystudio/node-cross-spawn/commit/16feb53))
<a name="6.0.5"></a>
## [6.0.5](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.4...v6.0.5) (2018-03-02)
### Bug Fixes
* avoid using deprecated Buffer constructor ([#94](https://github.com/moxystudio/node-cross-spawn/issues/94)) ([d5770df](https://github.com/moxystudio/node-cross-spawn/commit/d5770df)), closes [/nodejs.org/api/deprecations.html#deprecations_dep0005](https://github.com//nodejs.org/api/deprecations.html/issues/deprecations_dep0005)
<a name="6.0.4"></a>
## [6.0.4](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.3...v6.0.4) (2018-01-31)
### Bug Fixes
* fix paths being incorrectly normalized on unix ([06ee3c6](https://github.com/moxystudio/node-cross-spawn/commit/06ee3c6)), closes [#90](https://github.com/moxystudio/node-cross-spawn/issues/90)
<a name="6.0.3"></a>
## [6.0.3](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.2...v6.0.3) (2018-01-23)
<a name="6.0.2"></a>
## [6.0.2](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.1...v6.0.2) (2018-01-23)
<a name="6.0.1"></a>
## [6.0.1](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.0...v6.0.1) (2018-01-23)
<a name="6.0.0"></a>
# [6.0.0](https://github.com/moxystudio/node-cross-spawn/compare/5.1.0...6.0.0) (2018-01-23)
### Bug Fixes
* fix certain arguments not being correctly escaped or causing batch syntax error ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10)), closes [#82](https://github.com/moxystudio/node-cross-spawn/issues/82) [#51](https://github.com/moxystudio/node-cross-spawn/issues/51)
* fix commands as posix relatixe paths not working correctly, e.g.: `./my-command` ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10))
* fix `options` argument being mutated ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10))
* fix commands resolution when PATH was actually Path ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10))
### Features
* improve compliance with node's ENOENT errors ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10))
* improve detection of node's shell option support ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10))
### Chores
* upgrade tooling
* upgrate project to es6 (node v4)
### BREAKING CHANGES
* remove support for older nodejs versions, only `node >= 4` is supported
<a name="5.1.0"></a>
## [5.1.0](https://github.com/moxystudio/node-cross-spawn/compare/5.0.1...5.1.0) (2017-02-26)
### Bug Fixes
* fix `options.shell` support for NodeJS [v4.8](https://github.com/nodejs/node/blob/master/doc/changelogs/CHANGELOG_V4.md#4.8.0)
<a name="5.0.1"></a>
## [5.0.1](https://github.com/moxystudio/node-cross-spawn/compare/5.0.0...5.0.1) (2016-11-04)
### Bug Fixes
* fix `options.shell` support for NodeJS v7
<a name="5.0.0"></a>
# [5.0.0](https://github.com/moxystudio/node-cross-spawn/compare/4.0.2...5.0.0) (2016-10-30)
## Features
* add support for `options.shell`
* improve parsing of shebangs by using [`shebang-command`](https://github.com/kevva/shebang-command) module
## Chores
* refactor some code to make it more clear
* update README caveats
The MIT License (MIT)
Copyright (c) 2018 Made With MOXY Lda <hello@moxy.studio>
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.
# cross-spawn
[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Build status][appveyor-image]][appveyor-url] [![Coverage Status][codecov-image]][codecov-url] [![Dependency status][david-dm-image]][david-dm-url] [![Dev Dependency status][david-dm-dev-image]][david-dm-dev-url]
[npm-url]:https://npmjs.org/package/cross-spawn
[downloads-image]:http://img.shields.io/npm/dm/cross-spawn.svg
[npm-image]:http://img.shields.io/npm/v/cross-spawn.svg
[travis-url]:https://travis-ci.org/moxystudio/node-cross-spawn
[travis-image]:http://img.shields.io/travis/moxystudio/node-cross-spawn/master.svg
[appveyor-url]:https://ci.appveyor.com/project/satazor/node-cross-spawn
[appveyor-image]:https://img.shields.io/appveyor/ci/satazor/node-cross-spawn/master.svg
[codecov-url]:https://codecov.io/gh/moxystudio/node-cross-spawn
[codecov-image]:https://img.shields.io/codecov/c/github/moxystudio/node-cross-spawn/master.svg
[david-dm-url]:https://david-dm.org/moxystudio/node-cross-spawn
[david-dm-image]:https://img.shields.io/david/moxystudio/node-cross-spawn.svg
[david-dm-dev-url]:https://david-dm.org/moxystudio/node-cross-spawn?type=dev
[david-dm-dev-image]:https://img.shields.io/david/dev/moxystudio/node-cross-spawn.svg
A cross platform solution to node's spawn and spawnSync.
## Installation
Node.js version 8 and up:
`$ npm install cross-spawn`
Node.js version 7 and under:
`$ npm install cross-spawn@6`
## Why
Node has issues when using spawn on Windows:
- It ignores [PATHEXT](https://github.com/joyent/node/issues/2318)
- It does not support [shebangs](https://en.wikipedia.org/wiki/Shebang_(Unix))
- Has problems running commands with [spaces](https://github.com/nodejs/node/issues/7367)
- Has problems running commands with posix relative paths (e.g.: `./my-folder/my-executable`)
- Has an [issue](https://github.com/moxystudio/node-cross-spawn/issues/82) with command shims (files in `node_modules/.bin/`), where arguments with quotes and parenthesis would result in [invalid syntax error](https://github.com/moxystudio/node-cross-spawn/blob/e77b8f22a416db46b6196767bcd35601d7e11d54/test/index.test.js#L149)
- No `options.shell` support on node `<v4.8`
All these issues are handled correctly by `cross-spawn`.
There are some known modules, such as [win-spawn](https://github.com/ForbesLindesay/win-spawn), that try to solve this but they are either broken or provide faulty escaping of shell arguments.
## Usage
Exactly the same way as node's [`spawn`](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options) or [`spawnSync`](https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options), so it's a drop in replacement.
```js
const spawn = require('cross-spawn');
// Spawn NPM asynchronously
const child = spawn('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' });
// Spawn NPM synchronously
const result = spawn.sync('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' });
```
## Caveats
### Using `options.shell` as an alternative to `cross-spawn`
Starting from node `v4.8`, `spawn` has a `shell` option that allows you run commands from within a shell. This new option solves
the [PATHEXT](https://github.com/joyent/node/issues/2318) issue but:
- It's not supported in node `<v4.8`
- You must manually escape the command and arguments which is very error prone, specially when passing user input
- There are a lot of other unresolved issues from the [Why](#why) section that you must take into account
If you are using the `shell` option to spawn a command in a cross platform way, consider using `cross-spawn` instead. You have been warned.
### `options.shell` support
While `cross-spawn` adds support for `options.shell` in node `<v4.8`, all of its enhancements are disabled.
This mimics the Node.js behavior. More specifically, the command and its arguments will not be automatically escaped nor shebang support will be offered. This is by design because if you are using `options.shell` you are probably targeting a specific platform anyway and you don't want things to get into your way.
### Shebangs support
While `cross-spawn` handles shebangs on Windows, its support is limited. More specifically, it just supports `#!/usr/bin/env <program>` where `<program>` must not contain any arguments.
If you would like to have the shebang support improved, feel free to contribute via a pull-request.
Remember to always test your code on Windows!
## Tests
`$ npm test`
`$ npm test -- --watch` during development
## License
Released under the [MIT License](http://www.opensource.org/licenses/mit-license.php).
'use strict';
const cp = require('child_process');
const parse = require('./lib/parse');
const enoent = require('./lib/enoent');
function spawn(command, args, options) {
// Parse the arguments
const parsed = parse(command, args, options);
// Spawn the child process
const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
// Hook into child process "exit" event to emit an error if the command
// does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
enoent.hookChildProcess(spawned, parsed);
return spawned;
}
function spawnSync(command, args, options) {
// Parse the arguments
const parsed = parse(command, args, options);
// Spawn the child process
const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
// Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
return result;
}
module.exports = spawn;
module.exports.spawn = spawn;
module.exports.sync = spawnSync;
module.exports._parse = parse;
module.exports._enoent = enoent;
'use strict';
const isWin = process.platform === 'win32';
function notFoundError(original, syscall) {
return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
code: 'ENOENT',
errno: 'ENOENT',
syscall: `${syscall} ${original.command}`,
path: original.command,
spawnargs: original.args,
});
}
function hookChildProcess(cp, parsed) {
if (!isWin) {
return;
}
const originalEmit = cp.emit;
cp.emit = function (name, arg1) {
// If emitting "exit" event and exit code is 1, we need to check if
// the command exists and emit an "error" instead
// See https://github.com/IndigoUnited/node-cross-spawn/issues/16
if (name === 'exit') {
const err = verifyENOENT(arg1, parsed, 'spawn');
if (err) {
return originalEmit.call(cp, 'error', err);
}
}
return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params
};
}
function verifyENOENT(status, parsed) {
if (isWin && status === 1 && !parsed.file) {
return notFoundError(parsed.original, 'spawn');
}
return null;
}
function verifyENOENTSync(status, parsed) {
if (isWin && status === 1 && !parsed.file) {
return notFoundError(parsed.original, 'spawnSync');
}
return null;
}
module.exports = {
hookChildProcess,
verifyENOENT,
verifyENOENTSync,
notFoundError,
};
'use strict';
const path = require('path');
const resolveCommand = require('./util/resolveCommand');
const escape = require('./util/escape');
const readShebang = require('./util/readShebang');
const isWin = process.platform === 'win32';
const isExecutableRegExp = /\.(?:com|exe)$/i;
const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
function detectShebang(parsed) {
parsed.file = resolveCommand(parsed);
const shebang = parsed.file && readShebang(parsed.file);
if (shebang) {
parsed.args.unshift(parsed.file);
parsed.command = shebang;
return resolveCommand(parsed);
}
return parsed.file;
}
function parseNonShell(parsed) {
if (!isWin) {
return parsed;
}
// Detect & add support for shebangs
const commandFile = detectShebang(parsed);
// We don't need a shell if the command filename is an executable
const needsShell = !isExecutableRegExp.test(commandFile);
// If a shell is required, use cmd.exe and take care of escaping everything correctly
// Note that `forceShell` is an hidden option used only in tests
if (parsed.options.forceShell || needsShell) {
// Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`
// The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument
// Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,
// we need to double escape them
const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
// Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar)
// This is necessary otherwise it will always fail with ENOENT in those cases
parsed.command = path.normalize(parsed.command);
// Escape command & arguments
parsed.command = escape.command(parsed.command);
parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
const shellCommand = [parsed.command].concat(parsed.args).join(' ');
parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`];
parsed.command = process.env.comspec || 'cmd.exe';
parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped
}
return parsed;
}
function parse(command, args, options) {
// Normalize arguments, similar to nodejs
if (args && !Array.isArray(args)) {
options = args;
args = null;
}
args = args ? args.slice(0) : []; // Clone array to avoid changing the original
options = Object.assign({}, options); // Clone object to avoid changing the original
// Build our parsed object
const parsed = {
command,
args,
options,
file: undefined,
original: {
command,
args,
},
};
// Delegate further parsing to shell or non-shell
return options.shell ? parsed : parseNonShell(parsed);
}
module.exports = parse;
'use strict';
// See http://www.robvanderwoude.com/escapechars.php
const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
function escapeCommand(arg) {
// Escape meta chars
arg = arg.replace(metaCharsRegExp, '^$1');
return arg;
}
function escapeArgument(arg, doubleEscapeMetaChars) {
// Convert to string
arg = `${arg}`;
// Algorithm below is based on https://qntm.org/cmd
// Sequence of backslashes followed by a double quote:
// double up all the backslashes and escape the double quote
arg = arg.replace(/(\\*)"/g, '$1$1\\"');
// Sequence of backslashes followed by the end of the string
// (which will become a double quote later):
// double up all the backslashes
arg = arg.replace(/(\\*)$/, '$1$1');
// All other backslashes occur literally
// Quote the whole thing:
arg = `"${arg}"`;
// Escape meta chars
arg = arg.replace(metaCharsRegExp, '^$1');
// Double escape meta chars if necessary
if (doubleEscapeMetaChars) {
arg = arg.replace(metaCharsRegExp, '^$1');
}
return arg;
}
module.exports.command = escapeCommand;
module.exports.argument = escapeArgument;
'use strict';
const fs = require('fs');
const shebangCommand = require('shebang-command');
function readShebang(command) {
// Read the first 150 bytes from the file
const size = 150;
const buffer = Buffer.alloc(size);
let fd;
try {
fd = fs.openSync(command, 'r');
fs.readSync(fd, buffer, 0, size, 0);
fs.closeSync(fd);
} catch (e) { /* Empty */ }
// Attempt to extract shebang (null is returned if not a shebang)
return shebangCommand(buffer.toString());
}
module.exports = readShebang;
'use strict';
const path = require('path');
const which = require('which');
const pathKey = require('path-key')();
function resolveCommandAttempt(parsed, withoutPathExt) {
const cwd = process.cwd();
const hasCustomCwd = parsed.options.cwd != null;
// Worker threads do not have process.chdir()
const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined;
// If a custom `cwd` was specified, we need to change the process cwd
// because `which` will do stat calls but does not support a custom cwd
if (shouldSwitchCwd) {
try {
process.chdir(parsed.options.cwd);
} catch (err) {
/* Empty */
}
}
let resolved;
try {
resolved = which.sync(parsed.command, {
path: (parsed.options.env || process.env)[pathKey],
pathExt: withoutPathExt ? path.delimiter : undefined,
});
} catch (e) {
/* Empty */
} finally {
if (shouldSwitchCwd) {
process.chdir(cwd);
}
}
// If we successfully resolved, ensure that an absolute path is returned
// Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it
if (resolved) {
resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);
}
return resolved;
}
function resolveCommand(parsed) {
return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
}
module.exports = resolveCommand;
{
"_from": "cross-spawn@^7.0.0",
"_id": "cross-spawn@7.0.1",
"_inBundle": false,
"_integrity": "sha512-u7v4o84SwFpD32Z8IIcPZ6z1/ie24O6RU3RbtL5Y316l3KuHVPx9ItBgWQ6VlfAFnRnTtMUrsQ9MUUTuEZjogg==",
"_location": "/cross-spawn",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "cross-spawn@^7.0.0",
"name": "cross-spawn",
"escapedName": "cross-spawn",
"rawSpec": "^7.0.0",
"saveSpec": null,
"fetchSpec": "^7.0.0"
},
"_requiredBy": [
"/execa"
],
"_resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.1.tgz",
"_shasum": "0ab56286e0f7c24e153d04cc2aa027e43a9a5d14",
"_spec": "cross-spawn@^7.0.0",
"_where": "C:\\Users\\thequ\\Documents\\Mynij\\Mynij-unit-tests\\node_modules\\execa",
"author": {
"name": "André Cruz",
"email": "andre@moxy.studio"
},
"bugs": {
"url": "https://github.com/moxystudio/node-cross-spawn/issues"
},
"bundleDependencies": false,
"commitlint": {
"extends": [
"@commitlint/config-conventional"
]
},
"dependencies": {
"path-key": "^3.1.0",
"shebang-command": "^2.0.0",
"which": "^2.0.1"
},
"deprecated": false,
"description": "Cross platform child_process#spawn and child_process#spawnSync",
"devDependencies": {
"@commitlint/cli": "^8.1.0",
"@commitlint/config-conventional": "^8.1.0",
"babel-core": "^6.26.3",
"babel-jest": "^24.9.0",
"babel-preset-moxy": "^3.1.0",
"eslint": "^5.16.0",
"eslint-config-moxy": "^7.1.0",
"husky": "^3.0.5",
"jest": "^24.9.0",
"lint-staged": "^9.2.5",
"mkdirp": "^0.5.1",
"rimraf": "^3.0.0",
"standard-version": "^7.0.0"
},
"engines": {
"node": ">= 8"
},
"files": [
"lib"
],
"homepage": "https://github.com/moxystudio/node-cross-spawn",
"husky": {
"hooks": {
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS",
"pre-commit": "lint-staged"
}
},
"keywords": [
"spawn",
"spawnSync",
"windows",
"cross-platform",
"path-ext",
"shebang",
"cmd",
"execute"
],
"license": "MIT",
"lint-staged": {
"*.js": [
"eslint --fix",
"git add"
]
},
"main": "index.js",
"name": "cross-spawn",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/moxystudio/node-cross-spawn.git"
},
"scripts": {
"lint": "eslint .",
"prerelease": "npm t && npm run lint",
"release": "standard-version",
"test": "jest --env node --coverage"
},
"standard-version": {
"scripts": {
"posttag": "git push --follow-tags origin master"
}
},
"version": "7.0.1"
}
The MIT License (MIT)
Copyright (c) 2014 Mathias Buus
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
# end-of-stream
A node module that calls a callback when a readable/writable/duplex stream has completed or failed.
npm install end-of-stream
[![Build status](https://travis-ci.org/mafintosh/end-of-stream.svg?branch=master)](https://travis-ci.org/mafintosh/end-of-stream)
## Usage
Simply pass a stream and a callback to the `eos`.
Both legacy streams, streams2 and stream3 are supported.
``` js
var eos = require('end-of-stream');
eos(readableStream, function(err) {
// this will be set to the stream instance
if (err) return console.log('stream had an error or closed early');
console.log('stream has ended', this === readableStream);
});
eos(writableStream, function(err) {
if (err) return console.log('stream had an error or closed early');
console.log('stream has finished', this === writableStream);
});
eos(duplexStream, function(err) {
if (err) return console.log('stream had an error or closed early');
console.log('stream has ended and finished', this === duplexStream);
});
eos(duplexStream, {readable:false}, function(err) {
if (err) return console.log('stream had an error or closed early');
console.log('stream has finished but might still be readable');
});
eos(duplexStream, {writable:false}, function(err) {
if (err) return console.log('stream had an error or closed early');
console.log('stream has ended but might still be writable');
});
eos(readableStream, {error:false}, function(err) {
// do not treat emit('error', err) as a end-of-stream
});
```
## License
MIT
## Related
`end-of-stream` is part of the [mississippi stream utility collection](https://github.com/maxogden/mississippi) which includes more useful stream modules similar to this one.
var once = require('once');
var noop = function() {};
var isRequest = function(stream) {
return stream.setHeader && typeof stream.abort === 'function';
};
var isChildProcess = function(stream) {
return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3
};
var eos = function(stream, opts, callback) {
if (typeof opts === 'function') return eos(stream, null, opts);
if (!opts) opts = {};
callback = once(callback || noop);
var ws = stream._writableState;
var rs = stream._readableState;
var readable = opts.readable || (opts.readable !== false && stream.readable);
var writable = opts.writable || (opts.writable !== false && stream.writable);
var cancelled = false;
var onlegacyfinish = function() {
if (!stream.writable) onfinish();
};
var onfinish = function() {
writable = false;
if (!readable) callback.call(stream);
};
var onend = function() {
readable = false;
if (!writable) callback.call(stream);
};
var onexit = function(exitCode) {
callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);
};
var onerror = function(err) {
callback.call(stream, err);
};
var onclose = function() {
process.nextTick(onclosenexttick);
};
var onclosenexttick = function() {
if (cancelled) return;
if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close'));
if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close'));
};
var onrequest = function() {
stream.req.on('finish', onfinish);
};
if (isRequest(stream)) {
stream.on('complete', onfinish);
stream.on('abort', onclose);
if (stream.req) onrequest();
else stream.on('request', onrequest);
} else if (writable && !ws) { // legacy streams
stream.on('end', onlegacyfinish);
stream.on('close', onlegacyfinish);
}
if (isChildProcess(stream)) stream.on('exit', onexit);
stream.on('end', onend);
stream.on('finish', onfinish);
if (opts.error !== false) stream.on('error', onerror);
stream.on('close', onclose);
return function() {
cancelled = true;
stream.removeListener('complete', onfinish);
stream.removeListener('abort', onclose);
stream.removeListener('request', onrequest);
if (stream.req) stream.req.removeListener('finish', onfinish);
stream.removeListener('end', onlegacyfinish);
stream.removeListener('close', onlegacyfinish);
stream.removeListener('finish', onfinish);
stream.removeListener('exit', onexit);
stream.removeListener('end', onend);
stream.removeListener('error', onerror);
stream.removeListener('close', onclose);
};
};
module.exports = eos;
{
"_from": "end-of-stream@^1.1.0",
"_id": "end-of-stream@1.4.4",
"_inBundle": false,
"_integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==",
"_location": "/end-of-stream",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "end-of-stream@^1.1.0",
"name": "end-of-stream",
"escapedName": "end-of-stream",
"rawSpec": "^1.1.0",
"saveSpec": null,
"fetchSpec": "^1.1.0"
},
"_requiredBy": [
"/pump"
],
"_resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz",
"_shasum": "5ae64a5f45057baf3626ec14da0ca5e4b2431eb0",
"_spec": "end-of-stream@^1.1.0",
"_where": "C:\\Users\\thequ\\Documents\\Mynij\\Mynij-unit-tests\\node_modules\\pump",
"author": {
"name": "Mathias Buus",
"email": "mathiasbuus@gmail.com"
},
"bugs": {
"url": "https://github.com/mafintosh/end-of-stream/issues"
},
"bundleDependencies": false,
"dependencies": {
"once": "^1.4.0"
},
"deprecated": false,
"description": "Call a callback when a readable/writable/duplex stream has completed or failed.",
"devDependencies": {
"tape": "^4.11.0"
},
"files": [
"index.js"
],
"homepage": "https://github.com/mafintosh/end-of-stream",
"keywords": [
"stream",
"streams",
"callback",
"finish",
"close",
"end",
"wait"
],
"license": "MIT",
"main": "index.js",
"name": "end-of-stream",
"repository": {
"type": "git",
"url": "git://github.com/mafintosh/end-of-stream.git"
},
"scripts": {
"test": "node test.js"
},
"version": "1.4.4"
}
/// <reference types="node"/>
import {ChildProcess} from 'child_process';
import {Stream, Readable as ReadableStream} from 'stream';
declare namespace execa {
type StdioOption =
| 'pipe'
| 'ipc'
| 'ignore'
| 'inherit'
| Stream
| number
| undefined;
interface CommonOptions<EncodingType> {
/**
Kill the spawned process when the parent process exits unless either:
- the spawned process is [`detached`](https://nodejs.org/api/child_process.html#child_process_options_detached)
- the parent process is terminated abruptly, for example, with `SIGKILL` as opposed to `SIGTERM` or a normal exit
@default true
*/
readonly cleanup?: boolean;
/**
Prefer locally installed binaries when looking for a binary to execute.
If you `$ npm install foo`, you can then `execa('foo')`.
@default false
*/
readonly preferLocal?: boolean;
/**
Preferred path to find locally installed binaries in (use with `preferLocal`).
@default process.cwd()
*/
readonly localDir?: string;
/**
Path to the Node.js executable to use in child processes.
This can be either an absolute path or a path relative to the `cwd` option.
Requires `preferLocal` to be `true`.
For example, this can be used together with [`get-node`](https://github.com/ehmicky/get-node) to run a specific Node.js version in a child process.
@default process.execPath
*/
readonly execPath?: string;
/**
Buffer the output from the spawned process. When set to `false`, you must read the output of `stdout` and `stderr` (or `all` if the `all` option is `true`). Otherwise the returned promise will not be resolved/rejected.
If the spawned process fails, `error.stdout`, `error.stderr`, and `error.all` will contain the buffered data.
@default true
*/
readonly buffer?: boolean;
/**
Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).
@default 'pipe'
*/
readonly stdin?: StdioOption;
/**
Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).
@default 'pipe'
*/
readonly stdout?: StdioOption;
/**
Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).
@default 'pipe'
*/
readonly stderr?: StdioOption;
/**
Setting this to `false` resolves the promise with the error instead of rejecting it.
@default true
*/
readonly reject?: boolean;
/**
Add an `.all` property on the promise and the resolved value. The property contains the output of the process with `stdout` and `stderr` interleaved.
@default false
*/
readonly all?: boolean;
/**
Strip the final [newline character](https://en.wikipedia.org/wiki/Newline) from the output.
@default true
*/
readonly stripFinalNewline?: boolean;
/**
Set to `false` if you don't want to extend the environment variables when providing the `env` property.
@default true
*/
readonly extendEnv?: boolean;
/**
Current working directory of the child process.
@default process.cwd()
*/
readonly cwd?: string;
/**
Environment key-value pairs. Extends automatically from `process.env`. Set `extendEnv` to `false` if you don't want this.
@default process.env
*/
readonly env?: NodeJS.ProcessEnv;
/**
Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` or `file` if not specified.
*/
readonly argv0?: string;
/**
Child's [stdio](https://nodejs.org/api/child_process.html#child_process_options_stdio) configuration.
@default 'pipe'
*/
readonly stdio?: 'pipe' | 'ignore' | 'inherit' | readonly StdioOption[];
/**
Specify the kind of serialization used for sending messages between processes when using the `stdio: 'ipc'` option or `execa.node()`:
- `json`: Uses `JSON.stringify()` and `JSON.parse()`.
- `advanced`: Uses [`v8.serialize()`](https://nodejs.org/api/v8.html#v8_v8_serialize_value)
Requires Node.js `13.2.0` or later.
[More info.](https://nodejs.org/api/child_process.html#child_process_advanced_serialization)
@default 'json'
*/
readonly serialization?: 'json' | 'advanced';
/**
Prepare child to run independently of its parent process. Specific behavior [depends on the platform](https://nodejs.org/api/child_process.html#child_process_options_detached).
@default false
*/
readonly detached?: boolean;
/**
Sets the user identity of the process.
*/
readonly uid?: number;
/**
Sets the group identity of the process.
*/
readonly gid?: number;
/**
If `true`, runs `command` inside of a shell. Uses `/bin/sh` on UNIX and `cmd.exe` on Windows. A different shell can be specified as a string. The shell should understand the `-c` switch on UNIX or `/d /s /c` on Windows.
We recommend against using this option since it is:
- not cross-platform, encouraging shell-specific syntax.
- slower, because of the additional shell interpretation.
- unsafe, potentially allowing command injection.
@default false
*/
readonly shell?: boolean | string;
/**
Specify the character encoding used to decode the `stdout` and `stderr` output. If set to `null`, then `stdout` and `stderr` will be a `Buffer` instead of a string.
@default 'utf8'
*/
readonly encoding?: EncodingType;
/**
If `timeout` is greater than `0`, the parent will send the signal identified by the `killSignal` property (the default is `SIGTERM`) if the child runs longer than `timeout` milliseconds.
@default 0
*/
readonly timeout?: number;
/**
Largest amount of data in bytes allowed on `stdout` or `stderr`. Default: 100 MB.
@default 100_000_000
*/
readonly maxBuffer?: number;
/**
Signal value to be used when the spawned process will be killed.
@default 'SIGTERM'
*/
readonly killSignal?: string | number;
/**
If `true`, no quoting or escaping of arguments is done on Windows. Ignored on other platforms. This is set to `true` automatically when the `shell` option is `true`.
@default false
*/
readonly windowsVerbatimArguments?: boolean;
/**
On Windows, do not create a new console window. Please note this also prevents `CTRL-C` [from working](https://github.com/nodejs/node/issues/29837) on Windows.
@default true
*/
readonly windowsHide?: boolean;
}
interface Options<EncodingType = string> extends CommonOptions<EncodingType> {
/**
Write some input to the `stdin` of your binary.
*/
readonly input?: string | Buffer | ReadableStream;
}
interface SyncOptions<EncodingType = string> extends CommonOptions<EncodingType> {
/**
Write some input to the `stdin` of your binary.
*/
readonly input?: string | Buffer;
}
interface NodeOptions<EncodingType = string> extends Options<EncodingType> {
/**
The Node.js executable to use.
@default process.execPath
*/
readonly nodePath?: string;
/**
List of [CLI options](https://nodejs.org/api/cli.html#cli_options) passed to the Node.js executable.
@default process.execArgv
*/
readonly nodeOptions?: string[];
}
interface ExecaReturnBase<StdoutStderrType> {
/**
The file and arguments that were run.
*/
command: string;
/**
The numeric exit code of the process that was run.
*/
exitCode: number;
/**
The output of the process on stdout.
*/
stdout: StdoutStderrType;
/**
The output of the process on stderr.
*/
stderr: StdoutStderrType;
/**
Whether the process failed to run.
*/
failed: boolean;
/**
Whether the process timed out.
*/
timedOut: boolean;
/**
Whether the process was killed.
*/
killed: boolean;
/**
The name of the signal that was used to terminate the process. For example, `SIGFPE`.
If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`.
*/
signal?: string;
/**
A human-friendly description of the signal that was used to terminate the process. For example, `Floating point arithmetic error`.
If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`. It is also `undefined` when the signal is very uncommon which should seldomly happen.
*/
signalDescription?: string;
}
interface ExecaSyncReturnValue<StdoutErrorType = string>
extends ExecaReturnBase<StdoutErrorType> {
}
/**
Result of a child process execution. On success this is a plain object. On failure this is also an `Error` instance.
The child process fails when:
- its exit code is not `0`
- it was killed with a signal
- timing out
- being canceled
- there's not enough memory or there are already too many child processes
*/
interface ExecaReturnValue<StdoutErrorType = string>
extends ExecaSyncReturnValue<StdoutErrorType> {
/**
The output of the process with `stdout` and `stderr` interleaved.
This is `undefined` if either:
- the `all` option is `false` (default value)
- `execa.sync()` was used
*/
all?: StdoutErrorType;
/**
Whether the process was canceled.
*/
isCanceled: boolean;
}
interface ExecaSyncError<StdoutErrorType = string>
extends Error,
ExecaReturnBase<StdoutErrorType> {
/**
The error message.
*/
message: string;
/**
Original error message. This is `undefined` unless the child process exited due to an `error` event or a timeout.
The `message` property contains both the `originalMessage` and some additional information added by Execa.
*/
originalMessage?: string;
}
interface ExecaError<StdoutErrorType = string>
extends ExecaSyncError<StdoutErrorType> {
/**
The output of the process with `stdout` and `stderr` interleaved.
This is `undefined` if either:
- the `all` option is `false` (default value)
- `execa.sync()` was used
*/
all?: StdoutErrorType;
/**
Whether the process was canceled.
*/
isCanceled: boolean;
}
interface KillOptions {
/**
Milliseconds to wait for the child process to terminate before sending `SIGKILL`.
Can be disabled with `false`.
@default 5000
*/
forceKillAfterTimeout?: number | false;
}
interface ExecaChildPromise<StdoutErrorType> {
catch<ResultType = never>(
onRejected?: (reason: ExecaError<StdoutErrorType>) => ResultType | PromiseLike<ResultType>
): Promise<ExecaReturnValue<StdoutErrorType> | ResultType>;
/**
Same as the original [`child_process#kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal), except if `signal` is `SIGTERM` (the default value) and the child process is not terminated after 5 seconds, force it by sending `SIGKILL`.
*/
kill(signal?: string, options?: execa.KillOptions): void;
/**
Similar to [`childProcess.kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal). This is preferred when cancelling the child process execution as the error is more descriptive and [`childProcessResult.isCanceled`](#iscanceled) is set to `true`.
*/
cancel(): void;
/**
Stream combining/interleaving [`stdout`](https://nodejs.org/api/child_process.html#child_process_subprocess_stdout) and [`stderr`](https://nodejs.org/api/child_process.html#child_process_subprocess_stderr).
This is `undefined` if either:
- the `all` option is `false` (the default value)
- both `stdout` and `stderr` options are set to [`'inherit'`, `'ipc'`, `Stream` or `integer`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio)
*/
all?: ReadableStream;
}
type ExecaChildProcess<StdoutErrorType = string> = ChildProcess &
ExecaChildPromise<StdoutErrorType> &
Promise<ExecaReturnValue<StdoutErrorType>>;
}
declare const execa: {
/**
Execute a file.
Think of this as a mix of `child_process.execFile` and `child_process.spawn`.
@param file - The program/script to execute.
@param arguments - Arguments to pass to `file` on execution.
@returns A [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess), which is enhanced to also be a `Promise` for a result `Object` with `stdout` and `stderr` properties.
@example
```
import execa from 'execa';
(async () => {
const {stdout} = await execa('echo', ['unicorns']);
console.log(stdout);
//=> 'unicorns'
// Cancelling a spawned process
const subprocess = execa('node');
setTimeout(() => { spawned.cancel() }, 1000);
try {
await subprocess;
} catch (error) {
console.log(subprocess.killed); // true
console.log(error.isCanceled); // true
}
})();
// Pipe the child process stdout to the current stdout
execa('echo', ['unicorns']).stdout.pipe(process.stdout);
```
*/
(
file: string,
arguments?: readonly string[],
options?: execa.Options
): execa.ExecaChildProcess;
(
file: string,
arguments?: readonly string[],
options?: execa.Options<null>
): execa.ExecaChildProcess<Buffer>;
(file: string, options?: execa.Options): execa.ExecaChildProcess;
(file: string, options?: execa.Options<null>): execa.ExecaChildProcess<
Buffer
>;
/**
Execute a file synchronously.
This method throws an `Error` if the command fails.
@param file - The program/script to execute.
@param arguments - Arguments to pass to `file` on execution.
@returns A result `Object` with `stdout` and `stderr` properties.
*/
sync(
file: string,
arguments?: readonly string[],
options?: execa.SyncOptions
): execa.ExecaSyncReturnValue;
sync(
file: string,
arguments?: readonly string[],
options?: execa.SyncOptions<null>
): execa.ExecaSyncReturnValue<Buffer>;
sync(file: string, options?: execa.SyncOptions): execa.ExecaSyncReturnValue;
sync(
file: string,
options?: execa.SyncOptions<null>
): execa.ExecaSyncReturnValue<Buffer>;
/**
Same as `execa()` except both file and arguments are specified in a single `command` string. For example, `execa('echo', ['unicorns'])` is the same as `execa.command('echo unicorns')`.
If the file or an argument contains spaces, they must be escaped with backslashes. This matters especially if `command` is not a constant but a variable, for example with `__dirname` or `process.cwd()`. Except for spaces, no escaping/quoting is needed.
The `shell` option must be used if the `command` uses shell-specific features, as opposed to being a simple `file` followed by its `arguments`.
@param command - The program/script to execute and its arguments.
@returns A [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess), which is enhanced to also be a `Promise` for a result `Object` with `stdout` and `stderr` properties.
@example
```
import execa from 'execa';
(async () => {
const {stdout} = await execa.command('echo unicorns');
console.log(stdout);
//=> 'unicorns'
})();
```
*/
command(command: string, options?: execa.Options): execa.ExecaChildProcess;
command(command: string, options?: execa.Options<null>): execa.ExecaChildProcess<Buffer>;
/**
Same as `execa.command()` but synchronous.
@param command - The program/script to execute and its arguments.
@returns A result `Object` with `stdout` and `stderr` properties.
*/
commandSync(command: string, options?: execa.SyncOptions): execa.ExecaSyncReturnValue;
commandSync(command: string, options?: execa.SyncOptions<null>): execa.ExecaSyncReturnValue<Buffer>;
/**
Execute a Node.js script as a child process.
Same as `execa('node', [scriptPath, ...arguments], options)` except (like [`child_process#fork()`](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options)):
- the current Node version and options are used. This can be overridden using the `nodePath` and `nodeArguments` options.
- the `shell` option cannot be used
- an extra channel [`ipc`](https://nodejs.org/api/child_process.html#child_process_options_stdio) is passed to [`stdio`](#stdio)
@param scriptPath - Node.js script to execute.
@param arguments - Arguments to pass to `scriptPath` on execution.
@returns A [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess), which is enhanced to also be a `Promise` for a result `Object` with `stdout` and `stderr` properties.
*/
node(
scriptPath: string,
arguments?: readonly string[],
options?: execa.NodeOptions
): execa.ExecaChildProcess;
node(
scriptPath: string,
arguments?: readonly string[],
options?: execa.Options<null>
): execa.ExecaChildProcess<Buffer>;
node(scriptPath: string, options?: execa.Options): execa.ExecaChildProcess;
node(scriptPath: string, options?: execa.Options<null>): execa.ExecaChildProcess<Buffer>;
};
export = execa;
'use strict';
const path = require('path');
const childProcess = require('child_process');
const crossSpawn = require('cross-spawn');
const stripFinalNewline = require('strip-final-newline');
const npmRunPath = require('npm-run-path');
const onetime = require('onetime');
const makeError = require('./lib/error');
const normalizeStdio = require('./lib/stdio');
const {spawnedKill, spawnedCancel, setupTimeout, setExitHandler} = require('./lib/kill');
const {handleInput, getSpawnedResult, makeAllStream, validateInputSync} = require('./lib/stream.js');
const {mergePromise, getSpawnedPromise} = require('./lib/promise.js');
const {joinCommand, parseCommand} = require('./lib/command.js');
const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;
const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => {
const env = extendEnv ? {...process.env, ...envOption} : envOption;
if (preferLocal) {
return npmRunPath.env({env, cwd: localDir, execPath});
}
return env;
};
const handleArgs = (file, args, options = {}) => {
const parsed = crossSpawn._parse(file, args, options);
file = parsed.command;
args = parsed.args;
options = parsed.options;
options = {
maxBuffer: DEFAULT_MAX_BUFFER,
buffer: true,
stripFinalNewline: true,
extendEnv: true,
preferLocal: false,
localDir: options.cwd || process.cwd(),
execPath: process.execPath,
encoding: 'utf8',
reject: true,
cleanup: true,
all: false,
windowsHide: true,
...options
};
options.env = getEnv(options);
options.stdio = normalizeStdio(options);
if (process.platform === 'win32' && path.basename(file, '.exe') === 'cmd') {
// #116
args.unshift('/q');
}
return {file, args, options, parsed};
};
const handleOutput = (options, value, error) => {
if (typeof value !== 'string' && !Buffer.isBuffer(value)) {
// When `execa.sync()` errors, we normalize it to '' to mimic `execa()`
return error === undefined ? undefined : '';
}
if (options.stripFinalNewline) {
return stripFinalNewline(value);
}
return value;
};
const execa = (file, args, options) => {
const parsed = handleArgs(file, args, options);
const command = joinCommand(file, args);
let spawned;
try {
spawned = childProcess.spawn(parsed.file, parsed.args, parsed.options);
} catch (error) {
// Ensure the returned error is always both a promise and a child process
const dummySpawned = new childProcess.ChildProcess();
const errorPromise = Promise.reject(makeError({
error,
stdout: '',
stderr: '',
all: '',
command,
parsed,
timedOut: false,
isCanceled: false,
killed: false
}));
return mergePromise(dummySpawned, errorPromise);
}
const spawnedPromise = getSpawnedPromise(spawned);
const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise);
const processDone = setExitHandler(spawned, parsed.options, timedPromise);
const context = {isCanceled: false};
spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned));
spawned.cancel = spawnedCancel.bind(null, spawned, context);
const handlePromise = async () => {
const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone);
const stdout = handleOutput(parsed.options, stdoutResult);
const stderr = handleOutput(parsed.options, stderrResult);
const all = handleOutput(parsed.options, allResult);
if (error || exitCode !== 0 || signal !== null) {
const returnedError = makeError({
error,
exitCode,
signal,
stdout,
stderr,
all,
command,
parsed,
timedOut,
isCanceled: context.isCanceled,
killed: spawned.killed
});
if (!parsed.options.reject) {
return returnedError;
}
throw returnedError;
}
return {
command,
exitCode: 0,
stdout,
stderr,
all,
failed: false,
timedOut: false,
isCanceled: false,
killed: false
};
};
const handlePromiseOnce = onetime(handlePromise);
crossSpawn._enoent.hookChildProcess(spawned, parsed.parsed);
handleInput(spawned, parsed.options.input);
spawned.all = makeAllStream(spawned, parsed.options);
return mergePromise(spawned, handlePromiseOnce);
};
module.exports = execa;
module.exports.sync = (file, args, options) => {
const parsed = handleArgs(file, args, options);
const command = joinCommand(file, args);
validateInputSync(parsed.options);
let result;
try {
result = childProcess.spawnSync(parsed.file, parsed.args, parsed.options);
} catch (error) {
throw makeError({
error,
stdout: '',
stderr: '',
all: '',
command,
parsed,
timedOut: false,
isCanceled: false,
killed: false
});
}
const stdout = handleOutput(parsed.options, result.stdout, result.error);
const stderr = handleOutput(parsed.options, result.stderr, result.error);
if (result.error || result.status !== 0 || result.signal !== null) {
const error = makeError({
stdout,
stderr,
error: result.error,
signal: result.signal,
exitCode: result.status,
command,
parsed,
timedOut: result.error && result.error.code === 'ETIMEDOUT',
isCanceled: false,
killed: result.signal !== null
});
if (!parsed.options.reject) {
return error;
}
throw error;
}
return {
command,
exitCode: 0,
stdout,
stderr,
failed: false,
timedOut: false,
isCanceled: false,
killed: false
};
};
module.exports.command = (command, options) => {
const [file, ...args] = parseCommand(command);
return execa(file, args, options);
};
module.exports.commandSync = (command, options) => {
const [file, ...args] = parseCommand(command);
return execa.sync(file, args, options);
};
module.exports.node = (scriptPath, args, options = {}) => {
if (args && !Array.isArray(args) && typeof args === 'object') {
options = args;
args = [];
}
const stdio = normalizeStdio.node(options);
const {nodePath = process.execPath, nodeOptions = process.execArgv} = options;
return execa(
nodePath,
[
...nodeOptions,
scriptPath,
...(Array.isArray(args) ? args : [])
],
{
...options,
stdin: undefined,
stdout: undefined,
stderr: undefined,
stdio,
shell: false
}
);
};
'use strict';
const SPACES_REGEXP = / +/g;
const joinCommand = (file, args = []) => {
if (!Array.isArray(args)) {
return file;
}
return [file, ...args].join(' ');
};
// Allow spaces to be escaped by a backslash if not meant as a delimiter
const handleEscaping = (tokens, token, index) => {
if (index === 0) {
return [token];
}
const previousToken = tokens[tokens.length - 1];
if (previousToken.endsWith('\\')) {
return [...tokens.slice(0, -1), `${previousToken.slice(0, -1)} ${token}`];
}
return [...tokens, token];
};
// Handle `execa.command()`
const parseCommand = command => {
return command
.trim()
.split(SPACES_REGEXP)
.reduce(handleEscaping, []);
};
module.exports = {
joinCommand,
parseCommand
};
'use strict';
const {signalsByName} = require('human-signals');
const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => {
if (timedOut) {
return `timed out after ${timeout} milliseconds`;
}
if (isCanceled) {
return 'was canceled';
}
if (errorCode !== undefined) {
return `failed with ${errorCode}`;
}
if (signal !== undefined) {
return `was killed with ${signal} (${signalDescription})`;
}
if (exitCode !== undefined) {
return `failed with exit code ${exitCode}`;
}
return 'failed';
};
const makeError = ({
stdout,
stderr,
all,
error,
signal,
exitCode,
command,
timedOut,
isCanceled,
killed,
parsed: {options: {timeout}}
}) => {
// `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`.
// We normalize them to `undefined`
exitCode = exitCode === null ? undefined : exitCode;
signal = signal === null ? undefined : signal;
const signalDescription = signal === undefined ? undefined : signalsByName[signal].description;
const errorCode = error && error.code;
const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled});
const message = `Command ${prefix}: ${command}`;
if (error instanceof Error) {
error.originalMessage = error.message;
error.message = `${message}\n${error.message}`;
} else {
error = new Error(message);
}
error.command = command;
error.exitCode = exitCode;
error.signal = signal;
error.signalDescription = signalDescription;
error.stdout = stdout;
error.stderr = stderr;
if (all !== undefined) {
error.all = all;
}
if ('bufferedData' in error) {
delete error.bufferedData;
}
error.failed = true;
error.timedOut = Boolean(timedOut);
error.isCanceled = isCanceled;
error.killed = killed && !timedOut;
return error;
};
module.exports = makeError;
'use strict';
const os = require('os');
const onExit = require('signal-exit');
const pFinally = require('p-finally');
const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;
// Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior
const spawnedKill = (kill, signal = 'SIGTERM', options = {}) => {
const killResult = kill(signal);
setKillTimeout(kill, signal, options, killResult);
return killResult;
};
const setKillTimeout = (kill, signal, options, killResult) => {
if (!shouldForceKill(signal, options, killResult)) {
return;
}
const timeout = getForceKillAfterTimeout(options);
setTimeout(() => {
kill('SIGKILL');
}, timeout).unref();
};
const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => {
return isSigterm(signal) && forceKillAfterTimeout !== false && killResult;
};
const isSigterm = signal => {
return signal === os.constants.signals.SIGTERM ||
(typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM');
};
const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => {
if (forceKillAfterTimeout === true) {
return DEFAULT_FORCE_KILL_TIMEOUT;
}
if (!Number.isInteger(forceKillAfterTimeout) || forceKillAfterTimeout < 0) {
throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`);
}
return forceKillAfterTimeout;
};
// `childProcess.cancel()`
const spawnedCancel = (spawned, context) => {
const killResult = spawned.kill();
if (killResult) {
context.isCanceled = true;
}
};
const timeoutKill = (spawned, signal, reject) => {
spawned.kill(signal);
reject(Object.assign(new Error('Timed out'), {timedOut: true, signal}));
};
// `timeout` option handling
const setupTimeout = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => {
if (timeout === 0 || timeout === undefined) {
return spawnedPromise;
}
if (!Number.isInteger(timeout) || timeout < 0) {
throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);
}
let timeoutId;
const timeoutPromise = new Promise((resolve, reject) => {
timeoutId = setTimeout(() => {
timeoutKill(spawned, killSignal, reject);
}, timeout);
});
const safeSpawnedPromise = pFinally(spawnedPromise, () => {
clearTimeout(timeoutId);
});
return Promise.race([timeoutPromise, safeSpawnedPromise]);
};
// `cleanup` option handling
const setExitHandler = (spawned, {cleanup, detached}, timedPromise) => {
if (!cleanup || detached) {
return timedPromise;
}
const removeExitHandler = onExit(() => {
spawned.kill();
});
// TODO: Use native "finally" syntax when targeting Node.js 10
return pFinally(timedPromise, removeExitHandler);
};
module.exports = {
spawnedKill,
spawnedCancel,
setupTimeout,
setExitHandler
};
'use strict';
const mergePromiseProperty = (spawned, promise, property) => {
// Starting the main `promise` is deferred to avoid consuming streams
const value = typeof promise === 'function' ?
(...args) => promise()[property](...args) :
promise[property].bind(promise);
Object.defineProperty(spawned, property, {
value,
writable: true,
enumerable: false,
configurable: true
});
};
// The return value is a mixin of `childProcess` and `Promise`
const mergePromise = (spawned, promise) => {
mergePromiseProperty(spawned, promise, 'then');
mergePromiseProperty(spawned, promise, 'catch');
// TODO: Remove the `if`-guard when targeting Node.js 10
if (Promise.prototype.finally) {
mergePromiseProperty(spawned, promise, 'finally');
}
return spawned;
};
// Use promises instead of `child_process` events
const getSpawnedPromise = spawned => {
return new Promise((resolve, reject) => {
spawned.on('exit', (exitCode, signal) => {
resolve({exitCode, signal});
});
spawned.on('error', error => {
reject(error);
});
if (spawned.stdin) {
spawned.stdin.on('error', error => {
reject(error);
});
}
});
};
module.exports = {
mergePromise,
getSpawnedPromise
};
'use strict';
const aliases = ['stdin', 'stdout', 'stderr'];
const hasAlias = opts => aliases.some(alias => opts[alias] !== undefined);
const normalizeStdio = opts => {
if (!opts) {
return;
}
const {stdio} = opts;
if (stdio === undefined) {
return aliases.map(alias => opts[alias]);
}
if (hasAlias(opts)) {
throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`);
}
if (typeof stdio === 'string') {
return stdio;
}
if (!Array.isArray(stdio)) {
throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);
}
const length = Math.max(stdio.length, aliases.length);
return Array.from({length}, (value, index) => stdio[index]);
};
module.exports = normalizeStdio;
// `ipc` is pushed unless it is already present
module.exports.node = opts => {
const stdio = normalizeStdio(opts);
if (stdio === 'ipc') {
return 'ipc';
}
if (stdio === undefined || typeof stdio === 'string') {
return [stdio, stdio, stdio, 'ipc'];
}
if (stdio.includes('ipc')) {
return stdio;
}
return [...stdio, 'ipc'];
};
'use strict';
const isStream = require('is-stream');
const getStream = require('get-stream');
const mergeStream = require('merge-stream');
// `input` option
const handleInput = (spawned, input) => {
// Checking for stdin is workaround for https://github.com/nodejs/node/issues/26852
// TODO: Remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.0
if (input === undefined || spawned.stdin === undefined) {
return;
}
if (isStream(input)) {
input.pipe(spawned.stdin);
} else {
spawned.stdin.end(input);
}
};
// `all` interleaves `stdout` and `stderr`
const makeAllStream = (spawned, {all}) => {
if (!all || (!spawned.stdout && !spawned.stderr)) {
return;
}
const mixed = mergeStream();
if (spawned.stdout) {
mixed.add(spawned.stdout);
}
if (spawned.stderr) {
mixed.add(spawned.stderr);
}
return mixed;
};
// On failure, `result.stdout|stderr|all` should contain the currently buffered stream
const getBufferedData = async (stream, streamPromise) => {
if (!stream) {
return;
}
stream.destroy();
try {
return await streamPromise;
} catch (error) {
return error.bufferedData;
}
};
const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => {
if (!stream || !buffer) {
return;
}
if (encoding) {
return getStream(stream, {encoding, maxBuffer});
}
return getStream.buffer(stream, {maxBuffer});
};
// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)
const getSpawnedResult = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => {
const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer});
const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer});
const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2});
try {
return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]);
} catch (error) {
return Promise.all([
{error, signal: error.signal, timedOut: error.timedOut},
getBufferedData(stdout, stdoutPromise),
getBufferedData(stderr, stderrPromise),
getBufferedData(all, allPromise)
]);
}
};
const validateInputSync = ({input}) => {
if (isStream(input)) {
throw new TypeError('The `input` option cannot be a stream in sync mode');
}
};
module.exports = {
handleInput,
makeAllStream,
getSpawnedResult,
validateInputSync
};
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.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.
{
"_from": "execa",
"_id": "execa@3.4.0",
"_inBundle": false,
"_integrity": "sha512-r9vdGQk4bmCuK1yKQu1KTwcT2zwfWdbdaXfCtAh+5nU/4fSX+JAb7vZGvI5naJrQlvONrEB20jeruESI69530g==",
"_location": "/execa",
"_phantomChildren": {},
"_requested": {
"type": "tag",
"registry": true,
"raw": "execa",
"name": "execa",
"escapedName": "execa",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "latest"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/execa/-/execa-3.4.0.tgz",
"_shasum": "c08ed4550ef65d858fac269ffc8572446f37eb89",
"_spec": "execa",
"_where": "C:\\Users\\thequ\\Documents\\Mynij\\Mynij-unit-tests",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/execa/issues"
},
"bundleDependencies": false,
"dependencies": {
"cross-spawn": "^7.0.0",
"get-stream": "^5.0.0",
"human-signals": "^1.1.1",
"is-stream": "^2.0.0",
"merge-stream": "^2.0.0",
"npm-run-path": "^4.0.0",
"onetime": "^5.1.0",
"p-finally": "^2.0.0",
"signal-exit": "^3.0.2",
"strip-final-newline": "^2.0.0"
},
"deprecated": false,
"description": "Process execution for humans",
"devDependencies": {
"@types/node": "^12.0.7",
"ava": "^2.1.0",
"coveralls": "^3.0.4",
"get-node": "^5.0.0",
"is-running": "^2.1.0",
"nyc": "^14.1.1",
"p-event": "^4.1.0",
"tempfile": "^3.0.0",
"tsd": "^0.7.3",
"xo": "^0.24.0"
},
"engines": {
"node": "^8.12.0 || >=9.7.0"
},
"files": [
"index.js",
"index.d.ts",
"lib"
],
"homepage": "https://github.com/sindresorhus/execa#readme",
"keywords": [
"exec",
"child",
"process",
"execute",
"fork",
"execfile",
"spawn",
"file",
"shell",
"bin",
"binary",
"binaries",
"npm",
"path",
"local"
],
"license": "MIT",
"name": "execa",
"nyc": {
"exclude": [
"**/fixtures/**",
"**/test.js",
"**/test/**"
]
},
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/execa.git"
},
"scripts": {
"test": "xo && nyc ava && tsd"
},
"version": "3.4.0"
}
<img src="media/logo.svg" width="400">
<br>
[![Build Status](https://travis-ci.org/sindresorhus/execa.svg?branch=master)](https://travis-ci.org/sindresorhus/execa) [![Coverage Status](https://coveralls.io/repos/github/sindresorhus/execa/badge.svg?branch=master)](https://coveralls.io/github/sindresorhus/execa?branch=master)
> Process execution for humans
## Why
This package improves [`child_process`](https://nodejs.org/api/child_process.html) methods with:
- Promise interface.
- [Strips the final newline](#stripfinalnewline) from the output so you don't have to do `stdout.trim()`.
- Supports [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) binaries cross-platform.
- [Improved Windows support.](https://github.com/IndigoUnited/node-cross-spawn#why)
- Higher max buffer. 100 MB instead of 200 KB.
- [Executes locally installed binaries by name.](#preferlocal)
- [Cleans up spawned processes when the parent process dies.](#cleanup)
- [Get interleaved output](#all) from `stdout` and `stderr` similar to what is printed on the terminal. [*(Async only)*](#execasyncfile-arguments-options)
- [Can specify file and arguments as a single string without a shell](#execacommandcommand-options)
- More descriptive errors.
## Install
```
$ npm install execa
```
## Usage
```js
const execa = require('execa');
(async () => {
const {stdout} = await execa('echo', ['unicorns']);
console.log(stdout);
//=> 'unicorns'
})();
```
### Pipe the child process stdout to the parent
```js
const execa = require('execa');
execa('echo', ['unicorns']).stdout.pipe(process.stdout);
```
### Handling Errors
```js
const execa = require('execa');
(async () => {
// Catching an error
try {
await execa('unknown', ['command']);
} catch (error) {
console.log(error);
/*
{
message: 'Command failed with ENOENT: unknown command spawn unknown ENOENT',
errno: 'ENOENT',
code: 'ENOENT',
syscall: 'spawn unknown',
path: 'unknown',
spawnargs: ['command'],
originalMessage: 'spawn unknown ENOENT',
command: 'unknown command',
stdout: '',
stderr: '',
all: '',
failed: true,
timedOut: false,
isCanceled: false,
killed: false
}
*/
}
})();
```
### Cancelling a spawned process
```js
const execa = require('execa');
(async () => {
const subprocess = execa('node');
setTimeout(() => {
subprocess.cancel();
}, 1000);
try {
await subprocess;
} catch (error) {
console.log(subprocess.killed); // true
console.log(error.isCanceled); // true
}
})()
```
### Catching an error with the sync method
```js
try {
execa.sync('unknown', ['command']);
} catch (error) {
console.log(error);
/*
{
message: 'Command failed with ENOENT: unknown command spawnSync unknown ENOENT',
errno: 'ENOENT',
code: 'ENOENT',
syscall: 'spawnSync unknown',
path: 'unknown',
spawnargs: ['command'],
originalMessage: 'spawnSync unknown ENOENT',
command: 'unknown command',
stdout: '',
stderr: '',
all: '',
failed: true,
timedOut: false,
isCanceled: false,
killed: false
}
*/
}
```
### Kill a process
Using SIGTERM, and after 2 seconds, kill it with SIGKILL.
```js
const subprocess = execa('node');
setTimeout(() => {
subprocess.kill('SIGTERM', {
forceKillAfterTimeout: 2000
});
}, 1000);
```
## API
### execa(file, arguments, [options])
Execute a file. Think of this as a mix of [`child_process.execFile()`](https://nodejs.org/api/child_process.html#child_process_child_process_execfile_file_args_options_callback) and [`child_process.spawn()`](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options).
No escaping/quoting is needed.
Unless the [`shell`](#shell) option is used, no shell interpreter (Bash, `cmd.exe`, etc.) is used, so shell features such as variables substitution (`echo $PATH`) are not allowed.
Returns a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) which:
- is also a `Promise` resolving or rejecting with a [`childProcessResult`](#childProcessResult).
- exposes the following additional methods and properties.
#### kill([signal], [options])
Same as the original [`child_process#kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal) except: if `signal` is `SIGTERM` (the default value) and the child process is not terminated after 5 seconds, force it by sending `SIGKILL`.
##### options.forceKillAfterTimeout
Type: `number | false`<br>
Default: `5000`
Milliseconds to wait for the child process to terminate before sending `SIGKILL`.
Can be disabled with `false`.
#### cancel()
Similar to [`childProcess.kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal). This is preferred when cancelling the child process execution as the error is more descriptive and [`childProcessResult.isCanceled`](#iscanceled) is set to `true`.
#### all
Type: `ReadableStream | undefined`
Stream combining/interleaving [`stdout`](https://nodejs.org/api/child_process.html#child_process_subprocess_stdout) and [`stderr`](https://nodejs.org/api/child_process.html#child_process_subprocess_stderr).
This is `undefined` if either:
- the [`all` option](#all-2) is `false` (the default value)
- both [`stdout`](#stdout-1) and [`stderr`](#stderr-1) options are set to [`'inherit'`, `'ipc'`, `Stream` or `integer`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio)
### execa.sync(file, [arguments], [options])
Execute a file synchronously.
Returns or throws a [`childProcessResult`](#childProcessResult).
### execa.command(command, [options])
Same as [`execa()`](#execafile-arguments-options) except both file and arguments are specified in a single `command` string. For example, `execa('echo', ['unicorns'])` is the same as `execa.command('echo unicorns')`.
If the file or an argument contains spaces, they must be escaped with backslashes. This matters especially if `command` is not a constant but a variable, for example with `__dirname` or `process.cwd()`. Except for spaces, no escaping/quoting is needed.
The [`shell` option](#shell) must be used if the `command` uses shell-specific features, as opposed to being a simple `file` followed by its `arguments`.
### execa.commandSync(command, [options])
Same as [`execa.command()`](#execacommand-command-options) but synchronous.
Returns or throws a [`childProcessResult`](#childProcessResult).
### execa.node(scriptPath, [arguments], [options])
Execute a Node.js script as a child process.
Same as `execa('node', [scriptPath, ...arguments], options)` except (like [`child_process#fork()`](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options)):
- the current Node version and options are used. This can be overridden using the [`nodePath`](#nodepath-for-node-only) and [`nodeOptions`](#nodeoptions-for-node-only) options.
- the [`shell`](#shell) option cannot be used
- an extra channel [`ipc`](https://nodejs.org/api/child_process.html#child_process_options_stdio) is passed to [`stdio`](#stdio)
### childProcessResult
Type: `object`
Result of a child process execution. On success this is a plain object. On failure this is also an `Error` instance.
The child process [fails](#failed) when:
- its [exit code](#exitcode) is not `0`
- it was [killed](#killed) with a [signal](#signal)
- [timing out](#timedout)
- [being canceled](#iscanceled)
- there's not enough memory or there are already too many child processes
#### command
Type: `string`
The file and arguments that were run.
#### exitCode
Type: `number`
The numeric exit code of the process that was run.
#### stdout
Type: `string | Buffer`
The output of the process on stdout.
#### stderr
Type: `string | Buffer`
The output of the process on stderr.
#### all
Type: `string | Buffer | undefined`
The output of the process with `stdout` and `stderr` interleaved.
This is `undefined` if either:
- the [`all` option](#all-2) is `false` (the default value)
- `execa.sync()` was used
#### failed
Type: `boolean`
Whether the process failed to run.
#### timedOut
Type: `boolean`
Whether the process timed out.
#### isCanceled
Type: `boolean`
Whether the process was canceled.
#### killed
Type: `boolean`
Whether the process was killed.
#### signal
Type: `string | undefined`
The name of the signal that was used to terminate the process. For example, `SIGFPE`.
If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`.
#### signalDescription
Type: `string | undefined`
A human-friendly description of the signal that was used to terminate the process. For example, `Floating point arithmetic error`.
If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`. It is also `undefined` when the signal is very uncommon which should seldomly happen.
#### originalMessage
Type: `string | undefined`
Original error message. This is `undefined` unless the child process exited due to an `error` event or a timeout.
The `message` property contains both the `originalMessage` and some additional information added by Execa.
### options
Type: `object`
#### cleanup
Type: `boolean`<br>
Default: `true`
Kill the spawned process when the parent process exits unless either:
- the spawned process is [`detached`](https://nodejs.org/api/child_process.html#child_process_options_detached)
- the parent process is terminated abruptly, for example, with `SIGKILL` as opposed to `SIGTERM` or a normal exit
#### preferLocal
Type: `boolean`<br>
Default: `false`
Prefer locally installed binaries when looking for a binary to execute.<br>
If you `$ npm install foo`, you can then `execa('foo')`.
#### localDir
Type: `string`<br>
Default: `process.cwd()`
Preferred path to find locally installed binaries in (use with `preferLocal`).
#### execPath
Type: `string`<br>
Default: `process.execPath` (current Node.js executable)
Path to the Node.js executable to use in child processes.
This can be either an absolute path or a path relative to the [`cwd` option](#cwd).
Requires [`preferLocal`](#preferlocal) to be `true`.
For example, this can be used together with [`get-node`](https://github.com/ehmicky/get-node) to run a specific Node.js version in a child process.
#### buffer
Type: `boolean`<br>
Default: `true`
Buffer the output from the spawned process. When set to `false`, you must read the output of [`stdout`](#stdout-1) and [`stderr`](#stderr-1) (or [`all`](#all) if the [`all`](#all-2) option is `true`). Otherwise the returned promise will not be resolved/rejected.
If the spawned process fails, [`error.stdout`](#stdout), [`error.stderr`](#stderr), and [`error.all`](#all) will contain the buffered data.
#### input
Type: `string | Buffer | stream.Readable`
Write some input to the `stdin` of your binary.<br>
Streams are not allowed when using the synchronous methods.
#### stdin
Type: `string | number | Stream | undefined`<br>
Default: `pipe`
Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).
#### stdout
Type: `string | number | Stream | undefined`<br>
Default: `pipe`
Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).
#### stderr
Type: `string | number | Stream | undefined`<br>
Default: `pipe`
Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).
#### all
Type: `boolean`<br>
Default: `false`
Add an `.all` property on the [promise](#all) and the [resolved value](#all-1). The property contains the output of the process with `stdout` and `stderr` interleaved.
#### reject
Type: `boolean`<br>
Default: `true`
Setting this to `false` resolves the promise with the error instead of rejecting it.
#### stripFinalNewline
Type: `boolean`<br>
Default: `true`
Strip the final [newline character](https://en.wikipedia.org/wiki/Newline) from the output.
#### extendEnv
Type: `boolean`<br>
Default: `true`
Set to `false` if you don't want to extend the environment variables when providing the `env` property.
---
Execa also accepts the below options which are the same as the options for [`child_process#spawn()`](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options)/[`child_process#exec()`](https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback)
#### cwd
Type: `string`<br>
Default: `process.cwd()`
Current working directory of the child process.
#### env
Type: `object`<br>
Default: `process.env`
Environment key-value pairs. Extends automatically from `process.env`. Set [`extendEnv`](#extendenv) to `false` if you don't want this.
#### argv0
Type: `string`
Explicitly set the value of `argv[0]` sent to the child process. This will be set to `file` if not specified.
#### stdio
Type: `string | string[]`<br>
Default: `pipe`
Child's [stdio](https://nodejs.org/api/child_process.html#child_process_options_stdio) configuration.
#### serialization
Type: `string`<br>
Default: `'json'`
Specify the kind of serialization used for sending messages between processes when using the [`stdio: 'ipc'`](#stdio) option or [`execa.node()`](#execanodescriptpath-arguments-options):
- `json`: Uses `JSON.stringify()` and `JSON.parse()`.
- `advanced`: Uses [`v8.serialize()`](https://nodejs.org/api/v8.html#v8_v8_serialize_value)
Requires Node.js `13.2.0` or later.
[More info.](https://nodejs.org/api/child_process.html#child_process_advanced_serialization)
#### detached
Type: `boolean`
Prepare child to run independently of its parent process. Specific behavior [depends on the platform](https://nodejs.org/api/child_process.html#child_process_options_detached).
#### uid
Type: `number`
Sets the user identity of the process.
#### gid
Type: `number`
Sets the group identity of the process.
#### shell
Type: `boolean | string`<br>
Default: `false`
If `true`, runs `file` inside of a shell. Uses `/bin/sh` on UNIX and `cmd.exe` on Windows. A different shell can be specified as a string. The shell should understand the `-c` switch on UNIX or `/d /s /c` on Windows.
We recommend against using this option since it is:
- not cross-platform, encouraging shell-specific syntax.
- slower, because of the additional shell interpretation.
- unsafe, potentially allowing command injection.
#### encoding
Type: `string | null`<br>
Default: `utf8`
Specify the character encoding used to decode the `stdout` and `stderr` output. If set to `null`, then `stdout` and `stderr` will be a `Buffer` instead of a string.
#### timeout
Type: `number`<br>
Default: `0`
If timeout is greater than `0`, the parent will send the signal identified by the `killSignal` property (the default is `SIGTERM`) if the child runs longer than timeout milliseconds.
#### maxBuffer
Type: `number`<br>
Default: `100_000_000` (100 MB)
Largest amount of data in bytes allowed on `stdout` or `stderr`.
#### killSignal
Type: `string | number`<br>
Default: `SIGTERM`
Signal value to be used when the spawned process will be killed.
#### windowsVerbatimArguments
Type: `boolean`<br>
Default: `false`
If `true`, no quoting or escaping of arguments is done on Windows. Ignored on other platforms. This is set to `true` automatically when the `shell` option is `true`.
#### windowsHide
Type: `boolean`<br>
Default: `true`
On Windows, do not create a new console window. Please note this also prevents `CTRL-C` [from working](https://github.com/nodejs/node/issues/29837) on Windows.
#### nodePath *(for `.node()` only)*
Type: `string`<br>
Default: [`process.execPath`](https://nodejs.org/api/process.html#process_process_execpath)
Node.js executable used to create the child process.
#### nodeOptions *(for `.node()` only)*
Type: `string[]`<br>
Default: [`process.execArgv`](https://nodejs.org/api/process.html#process_process_execargv)
List of [CLI options](https://nodejs.org/api/cli.html#cli_options) passed to the Node.js executable.
## Tips
### Retry on error
Gracefully handle failures by using automatic retries and exponential backoff with the [`p-retry`](https://github.com/sindresorhus/p-retry) package:
```js
const pRetry = require('p-retry');
const run = async () => {
const results = await execa('curl', ['-sSL', 'https://sindresorhus.com/unicorn']);
return results;
};
(async () => {
console.log(await pRetry(run, {retries: 5}));
})();
```
### Save and pipe output from a child process
Let's say you want to show the output of a child process in real-time while also saving it to a variable.
```js
const execa = require('execa');
const subprocess = execa('echo', ['foo']);
subprocess.stdout.pipe(process.stdout);
(async () => {
const {stdout} = await subprocess;
console.log('child output:', stdout);
})();
```
### Redirect output to a file
```js
const execa = require('execa');
const subprocess = execa('echo', ['foo'])
subprocess.stdout.pipe(fs.createWriteStream('stdout.txt'))
```
### Redirect input from a file
```js
const execa = require('execa');
const subprocess = execa('cat')
fs.createReadStream('stdin.txt').pipe(subprocess.stdin)
```
### Execute the current package's binary
```js
const {getBinPathSync} = require('get-bin-path');
const binPath = getBinPathSync();
const subprocess = execa(binPath);
```
`execa` can be combined with [`get-bin-path`](https://github.com/ehmicky/get-bin-path) to test the current package's binary. As opposed to hard-coding the path to the binary, this validates that the `package.json` `bin` field is correctly set up.
## Related
- [gulp-execa](https://github.com/ehmicky/gulp-execa) - Gulp plugin for `execa`
## Maintainers
- [Sindre Sorhus](https://github.com/sindresorhus)
- [@ehmicky](https://github.com/ehmicky)
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-execa?utm_source=npm-execa&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>
'use strict';
const {PassThrough: PassThroughStream} = require('stream');
module.exports = options => {
options = {...options};
const {array} = options;
let {encoding} = options;
const isBuffer = encoding === 'buffer';
let objectMode = false;
if (array) {
objectMode = !(encoding || isBuffer);
} else {
encoding = encoding || 'utf8';
}
if (isBuffer) {
encoding = null;
}
const stream = new PassThroughStream({objectMode});
if (encoding) {
stream.setEncoding(encoding);
}
let length = 0;
const chunks = [];
stream.on('data', chunk => {
chunks.push(chunk);
if (objectMode) {
length = chunks.length;
} else {
length += chunk.length;
}
});
stream.getBufferedValue = () => {
if (array) {
return chunks;
}
return isBuffer ? Buffer.concat(chunks, length) : chunks.join('');
};
stream.getBufferedLength = () => length;
return stream;
};
/// <reference types="node"/>
import {Stream} from 'stream';
declare class MaxBufferErrorClass extends Error {
readonly name: 'MaxBufferError';
constructor();
}
declare namespace getStream {
interface Options {
/**
Maximum length of the returned string. If it exceeds this value before the stream ends, the promise will be rejected with a `MaxBufferError` error.
@default Infinity
*/
readonly maxBuffer?: number;
}
interface OptionsWithEncoding<EncodingType = BufferEncoding> extends Options {
/**
[Encoding](https://nodejs.org/api/buffer.html#buffer_buffer) of the incoming stream.
@default 'utf8'
*/
readonly encoding?: EncodingType;
}
type MaxBufferError = MaxBufferErrorClass;
}
declare const getStream: {
/**
Get the `stream` as a string.
@returns A promise that resolves when the end event fires on the stream, indicating that there is no more data to be read. The stream is switched to flowing mode.
@example
```
import * as fs from 'fs';
import getStream = require('get-stream');
(async () => {
const stream = fs.createReadStream('unicorn.txt');
console.log(await getStream(stream));
// ,,))))))));,
// __)))))))))))))),
// \|/ -\(((((''''((((((((.
// -*-==//////(('' . `)))))),
// /|\ ))| o ;-. '((((( ,(,
// ( `| / ) ;))))' ,_))^;(~
// | | | ,))((((_ _____------~~~-. %,;(;(>';'~
// o_); ; )))(((` ~---~ `:: \ %%~~)(v;(`('~
// ; ''''```` `: `:::|\,__,%% );`'; ~
// | _ ) / `:|`----' `-'
// ______/\/~ | / /
// /~;;.____/;;' / ___--,-( `;;;/
// / // _;______;'------~~~~~ /;;/\ /
// // | | / ; \;;,\
// (<_ | ; /',/-----' _>
// \_| ||_ //~;~~~~~~~~~
// `\_| (,~~
// \~\
// ~~
})();
```
*/
(stream: Stream, options?: getStream.OptionsWithEncoding): Promise<string>;
/**
Get the `stream` as a buffer.
It honors the `maxBuffer` option as above, but it refers to byte length rather than string length.
*/
buffer(
stream: Stream,
options?: getStream.OptionsWithEncoding
): Promise<Buffer>;
/**
Get the `stream` as an array of values.
It honors both the `maxBuffer` and `encoding` options. The behavior changes slightly based on the encoding chosen:
- When `encoding` is unset, it assumes an [object mode stream](https://nodesource.com/blog/understanding-object-streams/) and collects values emitted from `stream` unmodified. In this case `maxBuffer` refers to the number of items in the array (not the sum of their sizes).
- When `encoding` is set to `buffer`, it collects an array of buffers. `maxBuffer` refers to the summed byte lengths of every buffer in the array.
- When `encoding` is set to anything else, it collects an array of strings. `maxBuffer` refers to the summed character lengths of every string in the array.
*/
array<StreamObjectModeType = unknown>(
stream: Stream,
options?: getStream.Options
): Promise<StreamObjectModeType[]>;
array(
stream: Stream,
options: getStream.OptionsWithEncoding<'buffer'>
): Promise<Buffer[]>;
array(
stream: Stream,
options: getStream.OptionsWithEncoding<BufferEncoding>
): Promise<string[]>;
MaxBufferError: typeof MaxBufferErrorClass;
// TODO: Remove this for the next major release
default: typeof getStream;
};
export = getStream;
'use strict';
const pump = require('pump');
const bufferStream = require('./buffer-stream');
class MaxBufferError extends Error {
constructor() {
super('maxBuffer exceeded');
this.name = 'MaxBufferError';
}
}
async function getStream(inputStream, options) {
if (!inputStream) {
return Promise.reject(new Error('Expected a stream'));
}
options = {
maxBuffer: Infinity,
...options
};
const {maxBuffer} = options;
let stream;
await new Promise((resolve, reject) => {
const rejectPromise = error => {
if (error) { // A null check
error.bufferedData = stream.getBufferedValue();
}
reject(error);
};
stream = pump(inputStream, bufferStream(options), error => {
if (error) {
rejectPromise(error);
return;
}
resolve();
});
stream.on('data', () => {
if (stream.getBufferedLength() > maxBuffer) {
rejectPromise(new MaxBufferError());
}
});
});
return stream.getBufferedValue();
}
module.exports = getStream;
// TODO: Remove this for the next major release
module.exports.default = getStream;
module.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'});
module.exports.array = (stream, options) => getStream(stream, {...options, array: true});
module.exports.MaxBufferError = MaxBufferError;
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.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.
{
"_from": "get-stream@^5.0.0",
"_id": "get-stream@5.1.0",
"_inBundle": false,
"_integrity": "sha512-EXr1FOzrzTfGeL0gQdeFEvOMm2mzMOglyiOXSTpPC+iAjAKftbr3jpCMWynogwYnM+eSj9sHGc6wjIcDvYiygw==",
"_location": "/get-stream",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "get-stream@^5.0.0",
"name": "get-stream",
"escapedName": "get-stream",
"rawSpec": "^5.0.0",
"saveSpec": null,
"fetchSpec": "^5.0.0"
},
"_requiredBy": [
"/execa"
],
"_resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.1.0.tgz",
"_shasum": "01203cdc92597f9b909067c3e656cc1f4d3c4dc9",
"_spec": "get-stream@^5.0.0",
"_where": "C:\\Users\\thequ\\Documents\\Mynij\\Mynij-unit-tests\\node_modules\\execa",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/get-stream/issues"
},
"bundleDependencies": false,
"dependencies": {
"pump": "^3.0.0"
},
"deprecated": false,
"description": "Get a stream as a string, buffer, or array",
"devDependencies": {
"@types/node": "^11.13.0",
"ava": "^1.4.1",
"into-stream": "^5.0.0",
"tsd": "^0.7.2",
"xo": "^0.24.0"
},
"engines": {
"node": ">=8"
},
"files": [
"index.js",
"index.d.ts",
"buffer-stream.js"
],
"homepage": "https://github.com/sindresorhus/get-stream#readme",
"keywords": [
"get",
"stream",
"promise",
"concat",
"string",
"text",
"buffer",
"read",
"data",
"consume",
"readable",
"readablestream",
"array",
"object"
],
"license": "MIT",
"name": "get-stream",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/get-stream.git"
},
"scripts": {
"test": "xo && ava && tsd"
},
"version": "5.1.0"
}
# get-stream [![Build Status](https://travis-ci.org/sindresorhus/get-stream.svg?branch=master)](https://travis-ci.org/sindresorhus/get-stream)
> Get a stream as a string, buffer, or array
## Install
```
$ npm install get-stream
```
## Usage
```js
const fs = require('fs');
const getStream = require('get-stream');
(async () => {
const stream = fs.createReadStream('unicorn.txt');
console.log(await getStream(stream));
/*
,,))))))));,
__)))))))))))))),
\|/ -\(((((''''((((((((.
-*-==//////(('' . `)))))),
/|\ ))| o ;-. '((((( ,(,
( `| / ) ;))))' ,_))^;(~
| | | ,))((((_ _____------~~~-. %,;(;(>';'~
o_); ; )))(((` ~---~ `:: \ %%~~)(v;(`('~
; ''''```` `: `:::|\,__,%% );`'; ~
| _ ) / `:|`----' `-'
______/\/~ | / /
/~;;.____/;;' / ___--,-( `;;;/
/ // _;______;'------~~~~~ /;;/\ /
// | | / ; \;;,\
(<_ | ; /',/-----' _>
\_| ||_ //~;~~~~~~~~~
`\_| (,~~
\~\
~~
*/
})();
```
## API
The methods returns a promise that resolves when the `end` event fires on the stream, indicating that there is no more data to be read. The stream is switched to flowing mode.
### getStream(stream, [options])
Get the `stream` as a string.
#### options
Type: `Object`
##### encoding
Type: `string`<br>
Default: `utf8`
[Encoding](https://nodejs.org/api/buffer.html#buffer_buffer) of the incoming stream.
##### maxBuffer
Type: `number`<br>
Default: `Infinity`
Maximum length of the returned string. If it exceeds this value before the stream ends, the promise will be rejected with a `getStream.MaxBufferError` error.
### getStream.buffer(stream, [options])
Get the `stream` as a buffer.
It honors the `maxBuffer` option as above, but it refers to byte length rather than string length.
### getStream.array(stream, [options])
Get the `stream` as an array of values.
It honors both the `maxBuffer` and `encoding` options. The behavior changes slightly based on the encoding chosen:
- When `encoding` is unset, it assumes an [object mode stream](https://nodesource.com/blog/understanding-object-streams/) and collects values emitted from `stream` unmodified. In this case `maxBuffer` refers to the number of items in the array (not the sum of their sizes).
- When `encoding` is set to `buffer`, it collects an array of buffers. `maxBuffer` refers to the summed byte lengths of every buffer in the array.
- When `encoding` is set to anything else, it collects an array of strings. `maxBuffer` refers to the summed character lengths of every string in the array.
## Errors
If the input stream emits an `error` event, the promise will be rejected with the error. The buffered data will be attached to the `bufferedData` property of the error.
```js
(async () => {
try {
await getStream(streamThatErrorsAtTheEnd('unicorn'));
} catch (error) {
console.log(error.bufferedData);
//=> 'unicorn'
}
})()
```
## FAQ
### How is this different from [`concat-stream`](https://github.com/maxogden/concat-stream)?
This module accepts a stream instead of being one and returns a promise instead of using a callback. The API is simpler and it only supports returning a string, buffer, or array. It doesn't have a fragile type inference. You explicitly choose what you want. And it doesn't depend on the huge `readable-stream` package.
## Related
- [get-stdin](https://github.com/sindresorhus/get-stdin) - Get stdin as a string or buffer
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2019 ehmicky <ehmicky@gmail.com>
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.
[![Codecov](https://img.shields.io/codecov/c/github/ehmicky/human-signals.svg?label=tested&logo=codecov)](https://codecov.io/gh/ehmicky/human-signals)
[![Travis](https://img.shields.io/badge/cross-platform-4cc61e.svg?logo=travis)](https://travis-ci.org/ehmicky/human-signals)
[![Node](https://img.shields.io/node/v/human-signals.svg?logo=node.js)](https://www.npmjs.com/package/human-signals)
[![Gitter](https://img.shields.io/gitter/room/ehmicky/human-signals.svg?logo=gitter)](https://gitter.im/ehmicky/human-signals)
[![Twitter](https://img.shields.io/badge/%E2%80%8B-twitter-4cc61e.svg?logo=twitter)](https://twitter.com/intent/follow?screen_name=ehmicky)
[![Medium](https://img.shields.io/badge/%E2%80%8B-medium-4cc61e.svg?logo=medium)](https://medium.com/@ehmicky)
Human-friendly process signals.
This is a map of known process signals with some information about each signal.
Unlike
[`os.constants.signals`](https://nodejs.org/api/os.html#os_signal_constants)
this includes:
- human-friendly [descriptions](#description)
- [default actions](#action), including whether they [can be prevented](#forced)
- whether the signal is [supported](#supported) by the current OS
# Example
```js
const { signalsByName, signalsByNumber } = require('human-signals')
console.log(signalsByName.SIGINT)
// {
// name: 'SIGINT',
// number: 2,
// description: 'User interruption with CTRL-C',
// supported: true,
// action: 'terminate',
// forced: false,
// standard: 'ansi'
// }
console.log(signalsByNumber[8])
// {
// name: 'SIGFPE',
// number: 8,
// description: 'Floating point arithmetic error',
// supported: true,
// action: 'core',
// forced: false,
// standard: 'ansi'
// }
```
# Install
```bash
npm install human-signals
```
# Usage
## signalsByName
_Type_: `object`
Object whose keys are signal [names](#name) and values are
[signal objects](#signal).
## signalsByNumber
_Type_: `object`
Object whose keys are signal [numbers](#number) and values are
[signal objects](#signal).
## signal
_Type_: `object`
Signal object with the following properties.
### name
_Type_: `string`
Standard name of the signal, for example `'SIGINT'`.
### number
_Type_: `number`
Code number of the signal, for example `2`. While most `number` are
cross-platform, some are different between different OS.
### description
_Type_: `string`
Human-friendly description for the signal, for example
`'User interruption with CTRL-C'`.
### supported
_Type_: `boolean`
Whether the current OS can handle this signal in Node.js using
[`process.on(name, handler)`](https://nodejs.org/api/process.html#process_signal_events).
The list of supported signals
[is OS-specific](https://github.com/ehmicky/cross-platform-node-guide/blob/master/docs/6_networking_ipc/signals.md#cross-platform-signals).
### action
_Type_: `string`<br>_Enum_: `'terminate'`, `'core'`, `'ignore'`, `'pause'`,
`'unpause'`
What is the default action for this signal when it is not handled.
### forced
_Type_: `boolean`
Whether the signal's default action cannot be prevented. This is `true` for
`SIGTERM`, `SIGKILL` and `SIGSTOP`.
### standard
_Type_: `string`<br>_Enum_: `'ansi'`, `'posix'`, `'bsd'`, `'systemv'`, `'other'`
Which standard defined that signal.
# Support
If you found a bug or would like a new feature, _don't hesitate_ to
[submit an issue on GitHub](../../issues).
For other questions, feel free to
[chat with us on Gitter](https://gitter.im/ehmicky/human-signals).
Everyone is welcome regardless of personal background. We enforce a
[Code of conduct](CODE_OF_CONDUCT.md) in order to promote a positive and
inclusive environment.
# Contributing
This project was made with ❤️. The simplest way to give back is by starring and
sharing it online.
If the documentation is unclear or has a typo, please click on the page's `Edit`
button (pencil icon) and suggest a correction.
If you would like to help us fix a bug or add a new feature, please check our
[guidelines](CONTRIBUTING.md). Pull requests are welcome!
<!-- Thanks go to our wonderful contributors: -->
<!-- ALL-CONTRIBUTORS-LIST:START -->
<!-- prettier-ignore -->
<table><tr><td align="center"><a href="https://twitter.com/ehmicky"><img src="https://avatars2.githubusercontent.com/u/8136211?v=4" width="100px;" alt="ehmicky"/><br /><sub><b>ehmicky</b></sub></a><br /><a href="https://github.com/ehmicky/human-signals/commits?author=ehmicky" title="Code">💻</a> <a href="#design-ehmicky" title="Design">🎨</a> <a href="#ideas-ehmicky" title="Ideas, Planning, & Feedback">🤔</a> <a href="https://github.com/ehmicky/human-signals/commits?author=ehmicky" title="Documentation">📖</a></td></tr></table>
<!-- ALL-CONTRIBUTORS-LIST:END -->
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SIGNALS=void 0;
const SIGNALS=[
{
name:"SIGHUP",
number:1,
action:"terminate",
description:"Terminal closed",
standard:"posix"},
{
name:"SIGINT",
number:2,
action:"terminate",
description:"User interruption with CTRL-C",
standard:"ansi"},
{
name:"SIGQUIT",
number:3,
action:"core",
description:"User interruption with CTRL-\\",
standard:"posix"},
{
name:"SIGILL",
number:4,
action:"core",
description:"Invalid machine instruction",
standard:"ansi"},
{
name:"SIGTRAP",
number:5,
action:"core",
description:"Debugger breakpoint",
standard:"posix"},
{
name:"SIGABRT",
number:6,
action:"core",
description:"Aborted",
standard:"ansi"},
{
name:"SIGIOT",
number:6,
action:"core",
description:"Aborted",
standard:"bsd"},
{
name:"SIGBUS",
number:7,
action:"core",
description:
"Bus error due to misaligned, non-existing address or paging error",
standard:"bsd"},
{
name:"SIGEMT",
number:7,
action:"terminate",
description:"Command should be emulated but is not implemented",
standard:"other"},
{
name:"SIGFPE",
number:8,
action:"core",
description:"Floating point arithmetic error",
standard:"ansi"},
{
name:"SIGKILL",
number:9,
action:"terminate",
description:"Forced termination",
standard:"posix",
forced:true},
{
name:"SIGUSR1",
number:10,
action:"terminate",
description:"Application-specific signal",
standard:"posix"},
{
name:"SIGSEGV",
number:11,
action:"core",
description:"Segmentation fault",
standard:"ansi"},
{
name:"SIGUSR2",
number:12,
action:"terminate",
description:"Application-specific signal",
standard:"posix"},
{
name:"SIGPIPE",
number:13,
action:"terminate",
description:"Broken pipe or socket",
standard:"posix"},
{
name:"SIGALRM",
number:14,
action:"terminate",
description:"Timeout or timer",
standard:"posix"},
{
name:"SIGTERM",
number:15,
action:"terminate",
description:"Termination",
standard:"ansi"},
{
name:"SIGSTKFLT",
number:16,
action:"terminate",
description:"Stack is empty or overflowed",
standard:"other"},
{
name:"SIGCHLD",
number:17,
action:"ignore",
description:"Child process terminated, paused or unpaused",
standard:"posix"},
{
name:"SIGCLD",
number:17,
action:"ignore",
description:"Child process terminated, paused or unpaused",
standard:"other"},
{
name:"SIGCONT",
number:18,
action:"unpause",
description:"Unpaused",
standard:"posix",
forced:true},
{
name:"SIGSTOP",
number:19,
action:"pause",
description:"Paused",
standard:"posix",
forced:true},
{
name:"SIGTSTP",
number:20,
action:"pause",
description:"Paused using CTRL-Z or \"suspend\"",
standard:"posix"},
{
name:"SIGTTIN",
number:21,
action:"pause",
description:"Background process cannot read terminal input",
standard:"posix"},
{
name:"SIGBREAK",
number:21,
action:"terminate",
description:"User interruption with CTRL-BREAK",
standard:"other"},
{
name:"SIGTTOU",
number:22,
action:"pause",
description:"Background process cannot write to terminal output",
standard:"posix"},
{
name:"SIGURG",
number:23,
action:"ignore",
description:"Socket received out-of-band data",
standard:"bsd"},
{
name:"SIGXCPU",
number:24,
action:"core",
description:"Process timed out",
standard:"bsd"},
{
name:"SIGXFSZ",
number:25,
action:"core",
description:"File too big",
standard:"bsd"},
{
name:"SIGVTALRM",
number:26,
action:"terminate",
description:"Timeout or timer",
standard:"bsd"},
{
name:"SIGPROF",
number:27,
action:"terminate",
description:"Timeout or timer",
standard:"bsd"},
{
name:"SIGWINCH",
number:28,
action:"ignore",
description:"Terminal window size changed",
standard:"bsd"},
{
name:"SIGIO",
number:29,
action:"terminate",
description:"I/O is available",
standard:"other"},
{
name:"SIGPOLL",
number:29,
action:"terminate",
description:"Watched event",
standard:"other"},
{
name:"SIGINFO",
number:29,
action:"ignore",
description:"Request for process information",
standard:"other"},
{
name:"SIGPWR",
number:30,
action:"terminate",
description:"Device running out of power",
standard:"systemv"},
{
name:"SIGSYS",
number:31,
action:"core",
description:"Invalid system call",
standard:"other"},
{
name:"SIGUNUSED",
number:31,
action:"terminate",
description:"Invalid system call",
standard:"other"}];exports.SIGNALS=SIGNALS;
//# sourceMappingURL=core.js.map
\ No newline at end of file
{"version":3,"sources":["../../src/core.js"],"names":["SIGNALS","name","number","action","description","standard","forced"],"mappings":";;AAEO,KAAMA,CAAAA,OAAO,CAAG;AACrB;AACEC,IAAI,CAAE,QADR;AAEEC,MAAM,CAAE,CAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,iBAJf;AAKEC,QAAQ,CAAE,OALZ,CADqB;;AAQrB;AACEJ,IAAI,CAAE,QADR;AAEEC,MAAM,CAAE,CAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,+BAJf;AAKEC,QAAQ,CAAE,MALZ,CARqB;;AAerB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,CAFV;AAGEC,MAAM,CAAE,MAHV;AAIEC,WAAW,CAAE,gCAJf;AAKEC,QAAQ,CAAE,OALZ,CAfqB;;AAsBrB;AACEJ,IAAI,CAAE,QADR;AAEEC,MAAM,CAAE,CAFV;AAGEC,MAAM,CAAE,MAHV;AAIEC,WAAW,CAAE,6BAJf;AAKEC,QAAQ,CAAE,MALZ,CAtBqB;;AA6BrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,CAFV;AAGEC,MAAM,CAAE,MAHV;AAIEC,WAAW,CAAE,qBAJf;AAKEC,QAAQ,CAAE,OALZ,CA7BqB;;AAoCrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,CAFV;AAGEC,MAAM,CAAE,MAHV;AAIEC,WAAW,CAAE,SAJf;AAKEC,QAAQ,CAAE,MALZ,CApCqB;;AA2CrB;AACEJ,IAAI,CAAE,QADR;AAEEC,MAAM,CAAE,CAFV;AAGEC,MAAM,CAAE,MAHV;AAIEC,WAAW,CAAE,SAJf;AAKEC,QAAQ,CAAE,KALZ,CA3CqB;;AAkDrB;AACEJ,IAAI,CAAE,QADR;AAEEC,MAAM,CAAE,CAFV;AAGEC,MAAM,CAAE,MAHV;AAIEC,WAAW;AACT,mEALJ;AAMEC,QAAQ,CAAE,KANZ,CAlDqB;;AA0DrB;AACEJ,IAAI,CAAE,QADR;AAEEC,MAAM,CAAE,CAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,mDAJf;AAKEC,QAAQ,CAAE,OALZ,CA1DqB;;AAiErB;AACEJ,IAAI,CAAE,QADR;AAEEC,MAAM,CAAE,CAFV;AAGEC,MAAM,CAAE,MAHV;AAIEC,WAAW,CAAE,iCAJf;AAKEC,QAAQ,CAAE,MALZ,CAjEqB;;AAwErB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,CAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,oBAJf;AAKEC,QAAQ,CAAE,OALZ;AAMEC,MAAM,CAAE,IANV,CAxEqB;;AAgFrB;AACEL,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,6BAJf;AAKEC,QAAQ,CAAE,OALZ,CAhFqB;;AAuFrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,MAHV;AAIEC,WAAW,CAAE,oBAJf;AAKEC,QAAQ,CAAE,MALZ,CAvFqB;;AA8FrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,6BAJf;AAKEC,QAAQ,CAAE,OALZ,CA9FqB;;AAqGrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,uBAJf;AAKEC,QAAQ,CAAE,OALZ,CArGqB;;AA4GrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,kBAJf;AAKEC,QAAQ,CAAE,OALZ,CA5GqB;;AAmHrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,aAJf;AAKEC,QAAQ,CAAE,MALZ,CAnHqB;;AA0HrB;AACEJ,IAAI,CAAE,WADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,8BAJf;AAKEC,QAAQ,CAAE,OALZ,CA1HqB;;AAiIrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,QAHV;AAIEC,WAAW,CAAE,8CAJf;AAKEC,QAAQ,CAAE,OALZ,CAjIqB;;AAwIrB;AACEJ,IAAI,CAAE,QADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,QAHV;AAIEC,WAAW,CAAE,8CAJf;AAKEC,QAAQ,CAAE,OALZ,CAxIqB;;AA+IrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,SAHV;AAIEC,WAAW,CAAE,UAJf;AAKEC,QAAQ,CAAE,OALZ;AAMEC,MAAM,CAAE,IANV,CA/IqB;;AAuJrB;AACEL,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,OAHV;AAIEC,WAAW,CAAE,QAJf;AAKEC,QAAQ,CAAE,OALZ;AAMEC,MAAM,CAAE,IANV,CAvJqB;;AA+JrB;AACEL,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,OAHV;AAIEC,WAAW,CAAE,oCAJf;AAKEC,QAAQ,CAAE,OALZ,CA/JqB;;AAsKrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,OAHV;AAIEC,WAAW,CAAE,+CAJf;AAKEC,QAAQ,CAAE,OALZ,CAtKqB;;AA6KrB;AACEJ,IAAI,CAAE,UADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,mCAJf;AAKEC,QAAQ,CAAE,OALZ,CA7KqB;;AAoLrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,OAHV;AAIEC,WAAW,CAAE,oDAJf;AAKEC,QAAQ,CAAE,OALZ,CApLqB;;AA2LrB;AACEJ,IAAI,CAAE,QADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,QAHV;AAIEC,WAAW,CAAE,kCAJf;AAKEC,QAAQ,CAAE,KALZ,CA3LqB;;AAkMrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,MAHV;AAIEC,WAAW,CAAE,mBAJf;AAKEC,QAAQ,CAAE,KALZ,CAlMqB;;AAyMrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,MAHV;AAIEC,WAAW,CAAE,cAJf;AAKEC,QAAQ,CAAE,KALZ,CAzMqB;;AAgNrB;AACEJ,IAAI,CAAE,WADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,kBAJf;AAKEC,QAAQ,CAAE,KALZ,CAhNqB;;AAuNrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,kBAJf;AAKEC,QAAQ,CAAE,KALZ,CAvNqB;;AA8NrB;AACEJ,IAAI,CAAE,UADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,QAHV;AAIEC,WAAW,CAAE,8BAJf;AAKEC,QAAQ,CAAE,KALZ,CA9NqB;;AAqOrB;AACEJ,IAAI,CAAE,OADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,kBAJf;AAKEC,QAAQ,CAAE,OALZ,CArOqB;;AA4OrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,eAJf;AAKEC,QAAQ,CAAE,OALZ,CA5OqB;;AAmPrB;AACEJ,IAAI,CAAE,SADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,QAHV;AAIEC,WAAW,CAAE,iCAJf;AAKEC,QAAQ,CAAE,OALZ,CAnPqB;;AA0PrB;AACEJ,IAAI,CAAE,QADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,6BAJf;AAKEC,QAAQ,CAAE,SALZ,CA1PqB;;AAiQrB;AACEJ,IAAI,CAAE,QADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,MAHV;AAIEC,WAAW,CAAE,qBAJf;AAKEC,QAAQ,CAAE,OALZ,CAjQqB;;AAwQrB;AACEJ,IAAI,CAAE,WADR;AAEEC,MAAM,CAAE,EAFV;AAGEC,MAAM,CAAE,WAHV;AAIEC,WAAW,CAAE,qBAJf;AAKEC,QAAQ,CAAE,OALZ,CAxQqB,CAAhB,C","sourcesContent":["/* eslint-disable max-lines */\n// List of known process signals with information about them\nexport const SIGNALS = [\n {\n name: 'SIGHUP',\n number: 1,\n action: 'terminate',\n description: 'Terminal closed',\n standard: 'posix',\n },\n {\n name: 'SIGINT',\n number: 2,\n action: 'terminate',\n description: 'User interruption with CTRL-C',\n standard: 'ansi',\n },\n {\n name: 'SIGQUIT',\n number: 3,\n action: 'core',\n description: 'User interruption with CTRL-\\\\',\n standard: 'posix',\n },\n {\n name: 'SIGILL',\n number: 4,\n action: 'core',\n description: 'Invalid machine instruction',\n standard: 'ansi',\n },\n {\n name: 'SIGTRAP',\n number: 5,\n action: 'core',\n description: 'Debugger breakpoint',\n standard: 'posix',\n },\n {\n name: 'SIGABRT',\n number: 6,\n action: 'core',\n description: 'Aborted',\n standard: 'ansi',\n },\n {\n name: 'SIGIOT',\n number: 6,\n action: 'core',\n description: 'Aborted',\n standard: 'bsd',\n },\n {\n name: 'SIGBUS',\n number: 7,\n action: 'core',\n description:\n 'Bus error due to misaligned, non-existing address or paging error',\n standard: 'bsd',\n },\n {\n name: 'SIGEMT',\n number: 7,\n action: 'terminate',\n description: 'Command should be emulated but is not implemented',\n standard: 'other',\n },\n {\n name: 'SIGFPE',\n number: 8,\n action: 'core',\n description: 'Floating point arithmetic error',\n standard: 'ansi',\n },\n {\n name: 'SIGKILL',\n number: 9,\n action: 'terminate',\n description: 'Forced termination',\n standard: 'posix',\n forced: true,\n },\n {\n name: 'SIGUSR1',\n number: 10,\n action: 'terminate',\n description: 'Application-specific signal',\n standard: 'posix',\n },\n {\n name: 'SIGSEGV',\n number: 11,\n action: 'core',\n description: 'Segmentation fault',\n standard: 'ansi',\n },\n {\n name: 'SIGUSR2',\n number: 12,\n action: 'terminate',\n description: 'Application-specific signal',\n standard: 'posix',\n },\n {\n name: 'SIGPIPE',\n number: 13,\n action: 'terminate',\n description: 'Broken pipe or socket',\n standard: 'posix',\n },\n {\n name: 'SIGALRM',\n number: 14,\n action: 'terminate',\n description: 'Timeout or timer',\n standard: 'posix',\n },\n {\n name: 'SIGTERM',\n number: 15,\n action: 'terminate',\n description: 'Termination',\n standard: 'ansi',\n },\n {\n name: 'SIGSTKFLT',\n number: 16,\n action: 'terminate',\n description: 'Stack is empty or overflowed',\n standard: 'other',\n },\n {\n name: 'SIGCHLD',\n number: 17,\n action: 'ignore',\n description: 'Child process terminated, paused or unpaused',\n standard: 'posix',\n },\n {\n name: 'SIGCLD',\n number: 17,\n action: 'ignore',\n description: 'Child process terminated, paused or unpaused',\n standard: 'other',\n },\n {\n name: 'SIGCONT',\n number: 18,\n action: 'unpause',\n description: 'Unpaused',\n standard: 'posix',\n forced: true,\n },\n {\n name: 'SIGSTOP',\n number: 19,\n action: 'pause',\n description: 'Paused',\n standard: 'posix',\n forced: true,\n },\n {\n name: 'SIGTSTP',\n number: 20,\n action: 'pause',\n description: 'Paused using CTRL-Z or \"suspend\"',\n standard: 'posix',\n },\n {\n name: 'SIGTTIN',\n number: 21,\n action: 'pause',\n description: 'Background process cannot read terminal input',\n standard: 'posix',\n },\n {\n name: 'SIGBREAK',\n number: 21,\n action: 'terminate',\n description: 'User interruption with CTRL-BREAK',\n standard: 'other',\n },\n {\n name: 'SIGTTOU',\n number: 22,\n action: 'pause',\n description: 'Background process cannot write to terminal output',\n standard: 'posix',\n },\n {\n name: 'SIGURG',\n number: 23,\n action: 'ignore',\n description: 'Socket received out-of-band data',\n standard: 'bsd',\n },\n {\n name: 'SIGXCPU',\n number: 24,\n action: 'core',\n description: 'Process timed out',\n standard: 'bsd',\n },\n {\n name: 'SIGXFSZ',\n number: 25,\n action: 'core',\n description: 'File too big',\n standard: 'bsd',\n },\n {\n name: 'SIGVTALRM',\n number: 26,\n action: 'terminate',\n description: 'Timeout or timer',\n standard: 'bsd',\n },\n {\n name: 'SIGPROF',\n number: 27,\n action: 'terminate',\n description: 'Timeout or timer',\n standard: 'bsd',\n },\n {\n name: 'SIGWINCH',\n number: 28,\n action: 'ignore',\n description: 'Terminal window size changed',\n standard: 'bsd',\n },\n {\n name: 'SIGIO',\n number: 29,\n action: 'terminate',\n description: 'I/O is available',\n standard: 'other',\n },\n {\n name: 'SIGPOLL',\n number: 29,\n action: 'terminate',\n description: 'Watched event',\n standard: 'other',\n },\n {\n name: 'SIGINFO',\n number: 29,\n action: 'ignore',\n description: 'Request for process information',\n standard: 'other',\n },\n {\n name: 'SIGPWR',\n number: 30,\n action: 'terminate',\n description: 'Device running out of power',\n standard: 'systemv',\n },\n {\n name: 'SIGSYS',\n number: 31,\n action: 'core',\n description: 'Invalid system call',\n standard: 'other',\n },\n {\n name: 'SIGUNUSED',\n number: 31,\n action: 'terminate',\n description: 'Invalid system call',\n standard: 'other',\n },\n]\n/* eslint-enable max-lines */\n"],"file":"src/core.js"}
\ No newline at end of file
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.signalsByNumber=exports.signalsByName=void 0;var _os=require("os");
var _signals=require("./signals.js");
var _realtime=require("./realtime.js");
const getSignalsByName=function(){
const signals=(0,_signals.getSignals)();
return signals.reduce(getSignalByName,{});
};
const getSignalByName=function(
signalByNameMemo,
{name,number,description,supported,action,forced,standard})
{
return{
...signalByNameMemo,
[name]:{name,number,description,supported,action,forced,standard}};
};
const signalsByName=getSignalsByName();exports.signalsByName=signalsByName;
const getSignalsByNumber=function(){
const signals=(0,_signals.getSignals)();
const length=_realtime.SIGRTMAX+1;
const signalsA=Array.from({length},(value,number)=>
getSignalByNumber(number,signals));
return Object.assign({},...signalsA);
};
const getSignalByNumber=function(number,signals){
const signal=findSignalByNumber(number,signals);
if(signal===undefined){
return{};
}
const{name,description,supported,action,forced,standard}=signal;
return{
[number]:{
name,
number,
description,
supported,
action,
forced,
standard}};
};
const findSignalByNumber=function(number,signals){
const signal=signals.find(({name})=>_os.constants.signals[name]===number);
if(signal!==undefined){
return signal;
}
return signals.find(signalA=>signalA.number===number);
};
const signalsByNumber=getSignalsByNumber();exports.signalsByNumber=signalsByNumber;
//# sourceMappingURL=main.js.map
\ No newline at end of file
{"version":3,"sources":["../../src/main.js"],"names":["getSignalsByName","signals","reduce","getSignalByName","signalByNameMemo","name","number","description","supported","action","forced","standard","signalsByName","getSignalsByNumber","length","SIGRTMAX","signalsA","Array","from","value","getSignalByNumber","Object","assign","signal","findSignalByNumber","undefined","find","constants","signalA","signalsByNumber"],"mappings":"2HAAA;;AAEA;AACA;;;;AAIA,KAAMA,CAAAA,gBAAgB,CAAG,UAAW;AAClC,KAAMC,CAAAA,OAAO,CAAG,yBAAhB;AACA,MAAOA,CAAAA,OAAO,CAACC,MAAR,CAAeC,eAAf,CAAgC,EAAhC,CAAP;AACD,CAHD;;AAKA,KAAMA,CAAAA,eAAe,CAAG;AACtBC,gBADsB;AAEtB,CAAEC,IAAF,CAAQC,MAAR,CAAgBC,WAAhB,CAA6BC,SAA7B,CAAwCC,MAAxC,CAAgDC,MAAhD,CAAwDC,QAAxD,CAFsB;AAGtB;AACA,MAAO;AACL,GAAGP,gBADE;AAEL,CAACC,IAAD,EAAQ,CAAEA,IAAF,CAAQC,MAAR,CAAgBC,WAAhB,CAA6BC,SAA7B,CAAwCC,MAAxC,CAAgDC,MAAhD,CAAwDC,QAAxD,CAFH,CAAP;;AAID,CARD;;AAUO,KAAMC,CAAAA,aAAa,CAAGZ,gBAAgB,EAAtC,C;;;;;AAKP,KAAMa,CAAAA,kBAAkB,CAAG,UAAW;AACpC,KAAMZ,CAAAA,OAAO,CAAG,yBAAhB;AACA,KAAMa,CAAAA,MAAM,CAAGC,mBAAW,CAA1B;AACA,KAAMC,CAAAA,QAAQ,CAAGC,KAAK,CAACC,IAAN,CAAW,CAAEJ,MAAF,CAAX,CAAuB,CAACK,KAAD,CAAQb,MAAR;AACtCc,iBAAiB,CAACd,MAAD,CAASL,OAAT,CADF,CAAjB;;AAGA,MAAOoB,CAAAA,MAAM,CAACC,MAAP,CAAc,EAAd,CAAkB,GAAGN,QAArB,CAAP;AACD,CAPD;;AASA,KAAMI,CAAAA,iBAAiB,CAAG,SAASd,MAAT,CAAiBL,OAAjB,CAA0B;AAClD,KAAMsB,CAAAA,MAAM,CAAGC,kBAAkB,CAAClB,MAAD,CAASL,OAAT,CAAjC;;AAEA,GAAIsB,MAAM,GAAKE,SAAf,CAA0B;AACxB,MAAO,EAAP;AACD;;AAED,KAAM,CAAEpB,IAAF,CAAQE,WAAR,CAAqBC,SAArB,CAAgCC,MAAhC,CAAwCC,MAAxC,CAAgDC,QAAhD,EAA6DY,MAAnE;AACA,MAAO;AACL,CAACjB,MAAD,EAAU;AACRD,IADQ;AAERC,MAFQ;AAGRC,WAHQ;AAIRC,SAJQ;AAKRC,MALQ;AAMRC,MANQ;AAORC,QAPQ,CADL,CAAP;;;AAWD,CAnBD;;;;AAuBA,KAAMa,CAAAA,kBAAkB,CAAG,SAASlB,MAAT,CAAiBL,OAAjB,CAA0B;AACnD,KAAMsB,CAAAA,MAAM,CAAGtB,OAAO,CAACyB,IAAR,CAAa,CAAC,CAAErB,IAAF,CAAD,GAAcsB,cAAU1B,OAAV,CAAkBI,IAAlB,IAA4BC,MAAvD,CAAf;;AAEA,GAAIiB,MAAM,GAAKE,SAAf,CAA0B;AACxB,MAAOF,CAAAA,MAAP;AACD;;AAED,MAAOtB,CAAAA,OAAO,CAACyB,IAAR,CAAaE,OAAO,EAAIA,OAAO,CAACtB,MAAR,GAAmBA,MAA3C,CAAP;AACD,CARD;;AAUO,KAAMuB,CAAAA,eAAe,CAAGhB,kBAAkB,EAA1C,C","sourcesContent":["import { constants } from 'os'\n\nimport { getSignals } from './signals.js'\nimport { SIGRTMAX } from './realtime.js'\n\n// Retrieve `signalsByName`, an object mapping signal name to signal properties.\n// We make sure the object is sorted by `number`.\nconst getSignalsByName = function() {\n const signals = getSignals()\n return signals.reduce(getSignalByName, {})\n}\n\nconst getSignalByName = function(\n signalByNameMemo,\n { name, number, description, supported, action, forced, standard },\n) {\n return {\n ...signalByNameMemo,\n [name]: { name, number, description, supported, action, forced, standard },\n }\n}\n\nexport const signalsByName = getSignalsByName()\n\n// Retrieve `signalsByNumber`, an object mapping signal number to signal\n// properties.\n// We make sure the object is sorted by `number`.\nconst getSignalsByNumber = function() {\n const signals = getSignals()\n const length = SIGRTMAX + 1\n const signalsA = Array.from({ length }, (value, number) =>\n getSignalByNumber(number, signals),\n )\n return Object.assign({}, ...signalsA)\n}\n\nconst getSignalByNumber = function(number, signals) {\n const signal = findSignalByNumber(number, signals)\n\n if (signal === undefined) {\n return {}\n }\n\n const { name, description, supported, action, forced, standard } = signal\n return {\n [number]: {\n name,\n number,\n description,\n supported,\n action,\n forced,\n standard,\n },\n }\n}\n\n// Several signals might end up sharing the same number because of OS-specific\n// numbers, in which case those prevail.\nconst findSignalByNumber = function(number, signals) {\n const signal = signals.find(({ name }) => constants.signals[name] === number)\n\n if (signal !== undefined) {\n return signal\n }\n\n return signals.find(signalA => signalA.number === number)\n}\n\nexport const signalsByNumber = getSignalsByNumber()\n"],"file":"src/main.js"}
\ No newline at end of file
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SIGRTMAX=exports.getRealtimeSignals=void 0;
const getRealtimeSignals=function(){
const length=SIGRTMAX-SIGRTMIN+1;
return Array.from({length},getRealtimeSignal);
};exports.getRealtimeSignals=getRealtimeSignals;
const getRealtimeSignal=function(value,index){
return{
name:`SIGRT${index+1}`,
number:SIGRTMIN+index,
action:"terminate",
description:"Application-specific signal (realtime)",
standard:"posix"};
};
const SIGRTMIN=34;
const SIGRTMAX=64;exports.SIGRTMAX=SIGRTMAX;
//# sourceMappingURL=realtime.js.map
\ No newline at end of file
{"version":3,"sources":["../../src/realtime.js"],"names":["getRealtimeSignals","length","SIGRTMAX","SIGRTMIN","Array","from","getRealtimeSignal","value","index","name","number","action","description","standard"],"mappings":";AACO,KAAMA,CAAAA,kBAAkB,CAAG,UAAW;AAC3C,KAAMC,CAAAA,MAAM,CAAGC,QAAQ,CAAGC,QAAX,CAAsB,CAArC;AACA,MAAOC,CAAAA,KAAK,CAACC,IAAN,CAAW,CAAEJ,MAAF,CAAX,CAAuBK,iBAAvB,CAAP;AACD,CAHM,C;;AAKP,KAAMA,CAAAA,iBAAiB,CAAG,SAASC,KAAT,CAAgBC,KAAhB,CAAuB;AAC/C,MAAO;AACLC,IAAI,CAAG,QAAOD,KAAK,CAAG,CAAE,EADnB;AAELE,MAAM,CAAEP,QAAQ,CAAGK,KAFd;AAGLG,MAAM,CAAE,WAHH;AAILC,WAAW,CAAE,wCAJR;AAKLC,QAAQ,CAAE,OALL,CAAP;;AAOD,CARD;;AAUA,KAAMV,CAAAA,QAAQ,CAAG,EAAjB;AACO,KAAMD,CAAAA,QAAQ,CAAG,EAAjB,C","sourcesContent":["// List of realtime signals with information about them\nexport const getRealtimeSignals = function() {\n const length = SIGRTMAX - SIGRTMIN + 1\n return Array.from({ length }, getRealtimeSignal)\n}\n\nconst getRealtimeSignal = function(value, index) {\n return {\n name: `SIGRT${index + 1}`,\n number: SIGRTMIN + index,\n action: 'terminate',\n description: 'Application-specific signal (realtime)',\n standard: 'posix',\n }\n}\n\nconst SIGRTMIN = 34\nexport const SIGRTMAX = 64\n"],"file":"src/realtime.js"}
\ No newline at end of file
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.getSignals=void 0;var _os=require("os");
var _core=require("./core.js");
var _realtime=require("./realtime.js");
const getSignals=function(){
const realtimeSignals=(0,_realtime.getRealtimeSignals)();
const signals=[..._core.SIGNALS,...realtimeSignals].map(normalizeSignal);
return signals;
};exports.getSignals=getSignals;
const normalizeSignal=function({
name,
number:defaultNumber,
description,
action,
forced=false,
standard})
{
const{
signals:{[name]:constantSignal}}=
_os.constants;
const supported=constantSignal!==undefined;
const number=supported?constantSignal:defaultNumber;
return{name,number,description,supported,action,forced,standard};
};
//# sourceMappingURL=signals.js.map
\ No newline at end of file
{"version":3,"sources":["../../src/signals.js"],"names":["getSignals","realtimeSignals","signals","SIGNALS","map","normalizeSignal","name","number","defaultNumber","description","action","forced","standard","constantSignal","constants","supported","undefined"],"mappings":"gGAAA;;AAEA;AACA;;;;AAIO,KAAMA,CAAAA,UAAU,CAAG,UAAW;AACnC,KAAMC,CAAAA,eAAe,CAAG,kCAAxB;AACA,KAAMC,CAAAA,OAAO,CAAG,CAAC,GAAGC,aAAJ,CAAa,GAAGF,eAAhB,EAAiCG,GAAjC,CAAqCC,eAArC,CAAhB;AACA,MAAOH,CAAAA,OAAP;AACD,CAJM,C;;;;;;;;AAYP,KAAMG,CAAAA,eAAe,CAAG,SAAS;AAC/BC,IAD+B;AAE/BC,MAAM,CAAEC,aAFuB;AAG/BC,WAH+B;AAI/BC,MAJ+B;AAK/BC,MAAM,CAAG,KALsB;AAM/BC,QAN+B,CAAT;AAOrB;AACD,KAAM;AACJV,OAAO,CAAE,CAAE,CAACI,IAAD,EAAQO,cAAV,CADL;AAEFC,aAFJ;AAGA,KAAMC,CAAAA,SAAS,CAAGF,cAAc,GAAKG,SAArC;AACA,KAAMT,CAAAA,MAAM,CAAGQ,SAAS,CAAGF,cAAH,CAAoBL,aAA5C;AACA,MAAO,CAAEF,IAAF,CAAQC,MAAR,CAAgBE,WAAhB,CAA6BM,SAA7B,CAAwCL,MAAxC,CAAgDC,MAAhD,CAAwDC,QAAxD,CAAP;AACD,CAdD","sourcesContent":["import { constants } from 'os'\n\nimport { SIGNALS } from './core.js'\nimport { getRealtimeSignals } from './realtime.js'\n\n// Retrieve list of know signals (including realtime) with information about\n// them\nexport const getSignals = function() {\n const realtimeSignals = getRealtimeSignals()\n const signals = [...SIGNALS, ...realtimeSignals].map(normalizeSignal)\n return signals\n}\n\n// Normalize signal:\n// - `number`: signal numbers are OS-specific. This is taken into account by\n// `os.constants.signals`. However we provide a default `number` since some\n// signals are not defined for some OS.\n// - `forced`: set default to `false`\n// - `supported`: set value\nconst normalizeSignal = function({\n name,\n number: defaultNumber,\n description,\n action,\n forced = false,\n standard,\n}) {\n const {\n signals: { [name]: constantSignal },\n } = constants\n const supported = constantSignal !== undefined\n const number = supported ? constantSignal : defaultNumber\n return { name, number, description, supported, action, forced, standard }\n}\n"],"file":"src/signals.js"}
\ No newline at end of file
{
"_from": "human-signals@^1.1.1",
"_id": "human-signals@1.1.1",
"_inBundle": false,
"_integrity": "sha512-SEQu7vl8KjNL2eoGBLF3+wAjpsNfA9XMlXAYj/3EdaNfAlxKthD1xjEQfGOUhllCGGJVNY34bRr6lPINhNjyZw==",
"_location": "/human-signals",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "human-signals@^1.1.1",
"name": "human-signals",
"escapedName": "human-signals",
"rawSpec": "^1.1.1",
"saveSpec": null,
"fetchSpec": "^1.1.1"
},
"_requiredBy": [
"/execa"
],
"_resolved": "https://registry.npmjs.org/human-signals/-/human-signals-1.1.1.tgz",
"_shasum": "c5b1cd14f50aeae09ab6c59fe63ba3395fe4dfa3",
"_spec": "human-signals@^1.1.1",
"_where": "C:\\Users\\thequ\\Documents\\Mynij\\Mynij-unit-tests\\node_modules\\execa",
"author": {
"name": "ehmicky",
"email": "ehmicky@gmail.com",
"url": "https://github.com/ehmicky"
},
"bugs": {
"url": "https://github.com/ehmicky/human-signals/issues"
},
"bundleDependencies": false,
"dependencies": {},
"deprecated": false,
"description": "Human-friendly process signals",
"devDependencies": {
"@ehmicky/dev-tasks": "^0.30.48",
"ajv": "^6.10.2",
"ava": "^2.4.0",
"fast-deep-equal": "^2.0.1",
"gulp": "^4.0.2",
"husky": "^3.0.9",
"test-each": "^1.7.2"
},
"directories": {
"lib": "src",
"test": "test"
},
"engines": {
"node": ">=8.12.0"
},
"files": [
"build/src",
"!~"
],
"homepage": "https://git.io/JeluP",
"husky": {
"hooks": {
"pre-push": "gulp check --full"
}
},
"keywords": [
"signal",
"signals",
"handlers",
"error-handling",
"errors",
"interrupts",
"sigterm",
"sigint",
"irq",
"process",
"exit",
"exit-code",
"status",
"operating-system",
"es6",
"javascript",
"linux",
"macos",
"windows",
"nodejs"
],
"license": "Apache-2.0",
"main": "build/src/main.js",
"name": "human-signals",
"repository": {
"type": "git",
"url": "git+https://github.com/ehmicky/human-signals.git"
},
"scripts": {
"test": "gulp test"
},
"version": "1.1.1"
}
/// <reference types="node"/>
import * as stream from 'stream';
declare const isStream: {
/**
@returns Whether `stream` is a [`Stream`](https://nodejs.org/api/stream.html#stream_stream).
@example
```
import * as fs from 'fs';
import isStream = require('is-stream');
isStream(fs.createReadStream('unicorn.png'));
//=> true
isStream({});
//=> false
```
*/
(stream: unknown): stream is stream.Stream;
/**
@returns Whether `stream` is a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable).
@example
```
import * as fs from 'fs';
import isStream = require('is-stream');
isStream.writable(fs.createWriteStrem('unicorn.txt'));
//=> true
```
*/
writable(stream: unknown): stream is stream.Writable;
/**
@returns Whether `stream` is a [`stream.Readable`](https://nodejs.org/api/stream.html#stream_class_stream_readable).
@example
```
import * as fs from 'fs';
import isStream = require('is-stream');
isStream.readable(fs.createReadStream('unicorn.png'));
//=> true
```
*/
readable(stream: unknown): stream is stream.Readable;
/**
@returns Whether `stream` is a [`stream.Duplex`](https://nodejs.org/api/stream.html#stream_class_stream_duplex).
@example
```
import {Duplex} from 'stream';
import isStream = require('is-stream');
isStream.duplex(new Duplex());
//=> true
```
*/
duplex(stream: unknown): stream is stream.Duplex;
/**
@returns Whether `stream` is a [`stream.Transform`](https://nodejs.org/api/stream.html#stream_class_stream_transform).
@example
```
import * as fs from 'fs';
import Stringify = require('streaming-json-stringify');
import isStream = require('is-stream');
isStream.transform(Stringify());
//=> true
```
*/
transform(input: unknown): input is stream.Transform;
};
export = isStream;
'use strict';
const isStream = stream =>
stream !== null &&
typeof stream === 'object' &&
typeof stream.pipe === 'function';
isStream.writable = stream =>
isStream(stream) &&
stream.writable !== false &&
typeof stream._write === 'function' &&
typeof stream._writableState === 'object';
isStream.readable = stream =>
isStream(stream) &&
stream.readable !== false &&
typeof stream._read === 'function' &&
typeof stream._readableState === 'object';
isStream.duplex = stream =>
isStream.writable(stream) &&
isStream.readable(stream);
isStream.transform = stream =>
isStream.duplex(stream) &&
typeof stream._transform === 'function' &&
typeof stream._transformState === 'object';
module.exports = isStream;
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.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.
{
"_from": "is-stream@^2.0.0",
"_id": "is-stream@2.0.0",
"_inBundle": false,
"_integrity": "sha512-XCoy+WlUr7d1+Z8GgSuXmpuUFC9fOhRXglJMx+dwLKTkL44Cjd4W1Z5P+BQZpr+cR93aGP4S/s7Ftw6Nd/kiEw==",
"_location": "/is-stream",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "is-stream@^2.0.0",
"name": "is-stream",
"escapedName": "is-stream",
"rawSpec": "^2.0.0",
"saveSpec": null,
"fetchSpec": "^2.0.0"
},
"_requiredBy": [
"/execa"
],
"_resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.0.tgz",
"_shasum": "bde9c32680d6fae04129d6ac9d921ce7815f78e3",
"_spec": "is-stream@^2.0.0",
"_where": "C:\\Users\\thequ\\Documents\\Mynij\\Mynij-unit-tests\\node_modules\\execa",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/is-stream/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Check if something is a Node.js stream",
"devDependencies": {
"@types/node": "^11.13.6",
"ava": "^1.4.1",
"tempy": "^0.3.0",
"tsd": "^0.7.2",
"xo": "^0.24.0"
},
"engines": {
"node": ">=8"
},
"files": [
"index.js",
"index.d.ts"
],
"homepage": "https://github.com/sindresorhus/is-stream#readme",
"keywords": [
"stream",
"type",
"streams",
"writable",
"readable",
"duplex",
"transform",
"check",
"detect",
"is"
],
"license": "MIT",
"name": "is-stream",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/is-stream.git"
},
"scripts": {
"test": "xo && ava && tsd"
},
"version": "2.0.0"
}
# is-stream [![Build Status](https://travis-ci.org/sindresorhus/is-stream.svg?branch=master)](https://travis-ci.org/sindresorhus/is-stream)
> Check if something is a [Node.js stream](https://nodejs.org/api/stream.html)
## Install
```
$ npm install is-stream
```
## Usage
```js
const fs = require('fs');
const isStream = require('is-stream');
isStream(fs.createReadStream('unicorn.png'));
//=> true
isStream({});
//=> false
```
## API
### isStream(stream)
Returns a `boolean` for whether it's a [`Stream`](https://nodejs.org/api/stream.html#stream_stream).
#### isStream.writable(stream)
Returns a `boolean` for whether it's a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable).
#### isStream.readable(stream)
Returns a `boolean` for whether it's a [`stream.Readable`](https://nodejs.org/api/stream.html#stream_class_stream_readable).
#### isStream.duplex(stream)
Returns a `boolean` for whether it's a [`stream.Duplex`](https://nodejs.org/api/stream.html#stream_class_stream_duplex).
#### isStream.transform(stream)
Returns a `boolean` for whether it's a [`stream.Transform`](https://nodejs.org/api/stream.html#stream_class_stream_transform).
## Related
- [is-file-stream](https://github.com/jamestalmage/is-file-stream) - Detect if a stream is a file stream
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)
.nyc_output/
coverage/
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
# isexe
Minimal module to check if a file is executable, and a normal file.
Uses `fs.stat` and tests against the `PATHEXT` environment variable on
Windows.
## USAGE
```javascript
var isexe = require('isexe')
isexe('some-file-name', function (err, isExe) {
if (err) {
console.error('probably file does not exist or something', err)
} else if (isExe) {
console.error('this thing can be run')
} else {
console.error('cannot be run')
}
})
// same thing but synchronous, throws errors
var isExe = isexe.sync('some-file-name')
// treat errors as just "not executable"
isexe('maybe-missing-file', { ignoreErrors: true }, callback)
var isExe = isexe.sync('maybe-missing-file', { ignoreErrors: true })
```
## API
### `isexe(path, [options], [callback])`
Check if the path is executable. If no callback provided, and a
global `Promise` object is available, then a Promise will be returned.
Will raise whatever errors may be raised by `fs.stat`, unless
`options.ignoreErrors` is set to true.
### `isexe.sync(path, [options])`
Same as `isexe` but returns the value and throws any errors raised.
### Options
* `ignoreErrors` Treat all errors as "no, this is not executable", but
don't raise them.
* `uid` Number to use as the user id
* `gid` Number to use as the group id
* `pathExt` List of path extensions to use instead of `PATHEXT`
environment variable on Windows.
var fs = require('fs')
var core
if (process.platform === 'win32' || global.TESTING_WINDOWS) {
core = require('./windows.js')
} else {
core = require('./mode.js')
}
module.exports = isexe
isexe.sync = sync
function isexe (path, options, cb) {
if (typeof options === 'function') {
cb = options
options = {}
}
if (!cb) {
if (typeof Promise !== 'function') {
throw new TypeError('callback not provided')
}
return new Promise(function (resolve, reject) {
isexe(path, options || {}, function (er, is) {
if (er) {
reject(er)
} else {
resolve(is)
}
})
})
}
core(path, options || {}, function (er, is) {
// ignore EACCES because that just means we aren't allowed to run it
if (er) {
if (er.code === 'EACCES' || options && options.ignoreErrors) {
er = null
is = false
}
}
cb(er, is)
})
}
function sync (path, options) {
// my kingdom for a filtered catch
try {
return core.sync(path, options || {})
} catch (er) {
if (options && options.ignoreErrors || er.code === 'EACCES') {
return false
} else {
throw er
}
}
}
module.exports = isexe
isexe.sync = sync
var fs = require('fs')
function isexe (path, options, cb) {
fs.stat(path, function (er, stat) {
cb(er, er ? false : checkStat(stat, options))
})
}
function sync (path, options) {
return checkStat(fs.statSync(path), options)
}
function checkStat (stat, options) {
return stat.isFile() && checkMode(stat, options)
}
function checkMode (stat, options) {
var mod = stat.mode
var uid = stat.uid
var gid = stat.gid
var myUid = options.uid !== undefined ?
options.uid : process.getuid && process.getuid()
var myGid = options.gid !== undefined ?
options.gid : process.getgid && process.getgid()
var u = parseInt('100', 8)
var g = parseInt('010', 8)
var o = parseInt('001', 8)
var ug = u | g
var ret = (mod & o) ||
(mod & g) && gid === myGid ||
(mod & u) && uid === myUid ||
(mod & ug) && myUid === 0
return ret
}
{
"_from": "isexe@^2.0.0",
"_id": "isexe@2.0.0",
"_inBundle": false,
"_integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=",
"_location": "/isexe",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "isexe@^2.0.0",
"name": "isexe",
"escapedName": "isexe",
"rawSpec": "^2.0.0",
"saveSpec": null,
"fetchSpec": "^2.0.0"
},
"_requiredBy": [
"/which"
],
"_resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
"_shasum": "e8fbf374dc556ff8947a10dcb0572d633f2cfa10",
"_spec": "isexe@^2.0.0",
"_where": "C:\\Users\\thequ\\Documents\\Mynij\\Mynij-unit-tests\\node_modules\\which",
"author": {
"name": "Isaac Z. Schlueter",
"email": "i@izs.me",
"url": "http://blog.izs.me/"
},
"bugs": {
"url": "https://github.com/isaacs/isexe/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Minimal module to check if a file is executable.",
"devDependencies": {
"mkdirp": "^0.5.1",
"rimraf": "^2.5.0",
"tap": "^10.3.0"
},
"directories": {
"test": "test"
},
"homepage": "https://github.com/isaacs/isexe#readme",
"keywords": [],
"license": "ISC",
"main": "index.js",
"name": "isexe",
"repository": {
"type": "git",
"url": "git+https://github.com/isaacs/isexe.git"
},
"scripts": {
"postpublish": "git push origin --all; git push origin --tags",
"postversion": "npm publish",
"preversion": "npm test",
"test": "tap test/*.js --100"
},
"version": "2.0.0"
}
var t = require('tap')
var fs = require('fs')
var path = require('path')
var fixture = path.resolve(__dirname, 'fixtures')
var meow = fixture + '/meow.cat'
var mine = fixture + '/mine.cat'
var ours = fixture + '/ours.cat'
var fail = fixture + '/fail.false'
var noent = fixture + '/enoent.exe'
var mkdirp = require('mkdirp')
var rimraf = require('rimraf')
var isWindows = process.platform === 'win32'
var hasAccess = typeof fs.access === 'function'
var winSkip = isWindows && 'windows'
var accessSkip = !hasAccess && 'no fs.access function'
var hasPromise = typeof Promise === 'function'
var promiseSkip = !hasPromise && 'no global Promise'
function reset () {
delete require.cache[require.resolve('../')]
return require('../')
}
t.test('setup fixtures', function (t) {
rimraf.sync(fixture)
mkdirp.sync(fixture)
fs.writeFileSync(meow, '#!/usr/bin/env cat\nmeow\n')
fs.chmodSync(meow, parseInt('0755', 8))
fs.writeFileSync(fail, '#!/usr/bin/env false\n')
fs.chmodSync(fail, parseInt('0644', 8))
fs.writeFileSync(mine, '#!/usr/bin/env cat\nmine\n')
fs.chmodSync(mine, parseInt('0744', 8))
fs.writeFileSync(ours, '#!/usr/bin/env cat\nours\n')
fs.chmodSync(ours, parseInt('0754', 8))
t.end()
})
t.test('promise', { skip: promiseSkip }, function (t) {
var isexe = reset()
t.test('meow async', function (t) {
isexe(meow).then(function (is) {
t.ok(is)
t.end()
})
})
t.test('fail async', function (t) {
isexe(fail).then(function (is) {
t.notOk(is)
t.end()
})
})
t.test('noent async', function (t) {
isexe(noent).catch(function (er) {
t.ok(er)
t.end()
})
})
t.test('noent ignore async', function (t) {
isexe(noent, { ignoreErrors: true }).then(function (is) {
t.notOk(is)
t.end()
})
})
t.end()
})
t.test('no promise', function (t) {
global.Promise = null
var isexe = reset()
t.throws('try to meow a promise', function () {
isexe(meow)
})
t.end()
})
t.test('access', { skip: accessSkip || winSkip }, function (t) {
runTest(t)
})
t.test('mode', { skip: winSkip }, function (t) {
delete fs.access
delete fs.accessSync
var isexe = reset()
t.ok(isexe.sync(ours, { uid: 0, gid: 0 }))
t.ok(isexe.sync(mine, { uid: 0, gid: 0 }))
runTest(t)
})
t.test('windows', function (t) {
global.TESTING_WINDOWS = true
var pathExt = '.EXE;.CAT;.CMD;.COM'
t.test('pathExt option', function (t) {
runTest(t, { pathExt: '.EXE;.CAT;.CMD;.COM' })
})
t.test('pathExt env', function (t) {
process.env.PATHEXT = pathExt
runTest(t)
})
t.test('no pathExt', function (t) {
// with a pathExt of '', any filename is fine.
// so the "fail" one would still pass.
runTest(t, { pathExt: '', skipFail: true })
})
t.test('pathext with empty entry', function (t) {
// with a pathExt of '', any filename is fine.
// so the "fail" one would still pass.
runTest(t, { pathExt: ';' + pathExt, skipFail: true })
})
t.end()
})
t.test('cleanup', function (t) {
rimraf.sync(fixture)
t.end()
})
function runTest (t, options) {
var isexe = reset()
var optionsIgnore = Object.create(options || {})
optionsIgnore.ignoreErrors = true
if (!options || !options.skipFail) {
t.notOk(isexe.sync(fail, options))
}
t.notOk(isexe.sync(noent, optionsIgnore))
if (!options) {
t.ok(isexe.sync(meow))
} else {
t.ok(isexe.sync(meow, options))
}
t.ok(isexe.sync(mine, options))
t.ok(isexe.sync(ours, options))
t.throws(function () {
isexe.sync(noent, options)
})
t.test('meow async', function (t) {
if (!options) {
isexe(meow, function (er, is) {
if (er) {
throw er
}
t.ok(is)
t.end()
})
} else {
isexe(meow, options, function (er, is) {
if (er) {
throw er
}
t.ok(is)
t.end()
})
}
})
t.test('mine async', function (t) {
isexe(mine, options, function (er, is) {
if (er) {
throw er
}
t.ok(is)
t.end()
})
})
t.test('ours async', function (t) {
isexe(ours, options, function (er, is) {
if (er) {
throw er
}
t.ok(is)
t.end()
})
})
if (!options || !options.skipFail) {
t.test('fail async', function (t) {
isexe(fail, options, function (er, is) {
if (er) {
throw er
}
t.notOk(is)
t.end()
})
})
}
t.test('noent async', function (t) {
isexe(noent, options, function (er, is) {
t.ok(er)
t.notOk(is)
t.end()
})
})
t.test('noent ignore async', function (t) {
isexe(noent, optionsIgnore, function (er, is) {
if (er) {
throw er
}
t.notOk(is)
t.end()
})
})
t.test('directory is not executable', function (t) {
isexe(__dirname, options, function (er, is) {
if (er) {
throw er
}
t.notOk(is)
t.end()
})
})
t.end()
}
module.exports = isexe
isexe.sync = sync
var fs = require('fs')
function checkPathExt (path, options) {
var pathext = options.pathExt !== undefined ?
options.pathExt : process.env.PATHEXT
if (!pathext) {
return true
}
pathext = pathext.split(';')
if (pathext.indexOf('') !== -1) {
return true
}
for (var i = 0; i < pathext.length; i++) {
var p = pathext[i].toLowerCase()
if (p && path.substr(-p.length).toLowerCase() === p) {
return true
}
}
return false
}
function checkStat (stat, path, options) {
if (!stat.isSymbolicLink() && !stat.isFile()) {
return false
}
return checkPathExt(path, options)
}
function isexe (path, options, cb) {
fs.stat(path, function (er, stat) {
cb(er, er ? false : checkStat(stat, path, options))
})
}
function sync (path, options) {
return checkStat(fs.statSync(path), path, options)
}
The MIT License (MIT)
Copyright (c) Stephen Sugden <me@stephensugden.com> (stephensugden.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.
# merge-stream
Merge (interleave) a bunch of streams.
[![build status](https://secure.travis-ci.org/grncdr/merge-stream.svg?branch=master)](http://travis-ci.org/grncdr/merge-stream)
## Synopsis
```javascript
var stream1 = new Stream();
var stream2 = new Stream();
var merged = mergeStream(stream1, stream2);
var stream3 = new Stream();
merged.add(stream3);
merged.isEmpty();
//=> false
```
## Description
This is adapted from [event-stream](https://github.com/dominictarr/event-stream) separated into a new module, using Streams3.
## API
### `mergeStream`
Type: `function`
Merges an arbitrary number of streams. Returns a merged stream.
#### `merged.add`
A method to dynamically add more sources to the stream. The argument supplied to `add` can be either a source or an array of sources.
#### `merged.isEmpty`
A method that tells you if the merged stream is empty.
When a stream is "empty" (aka. no sources were added), it could not be returned to a gulp task.
So, we could do something like this:
```js
stream = require('merge-stream')();
// Something like a loop to add some streams to the merge stream
// stream.add(streamA);
// stream.add(streamB);
return stream.isEmpty() ? null : stream;
```
## Gulp example
An example use case for **merge-stream** is to combine parts of a task in a project's **gulpfile.js** like this:
```js
const gulp = require('gulp');
const htmlValidator = require('gulp-w3c-html-validator');
const jsHint = require('gulp-jshint');
const mergeStream = require('merge-stream');
function lint() {
return mergeStream(
gulp.src('src/*.html')
.pipe(htmlValidator())
.pipe(htmlValidator.reporter()),
gulp.src('src/*.js')
.pipe(jsHint())
.pipe(jsHint.reporter())
);
}
gulp.task('lint', lint);
```
## License
MIT
'use strict';
const { PassThrough } = require('stream');
module.exports = function (/*streams...*/) {
var sources = []
var output = new PassThrough({objectMode: true})
output.setMaxListeners(0)
output.add = add
output.isEmpty = isEmpty
output.on('unpipe', remove)
Array.prototype.slice.call(arguments).forEach(add)
return output
function add (source) {
if (Array.isArray(source)) {
source.forEach(add)
return this
}
sources.push(source);
source.once('end', remove.bind(null, source))
source.once('error', output.emit.bind(output, 'error'))
source.pipe(output, {end: false})
return this
}
function isEmpty () {
return sources.length == 0;
}
function remove (source) {
sources = sources.filter(function (it) { return it !== source })
if (!sources.length && output.readable) { output.end() }
}
}
{
"_from": "merge-stream@^2.0.0",
"_id": "merge-stream@2.0.0",
"_inBundle": false,
"_integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==",
"_location": "/merge-stream",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "merge-stream@^2.0.0",
"name": "merge-stream",
"escapedName": "merge-stream",
"rawSpec": "^2.0.0",
"saveSpec": null,
"fetchSpec": "^2.0.0"
},
"_requiredBy": [
"/execa"
],
"_resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",
"_shasum": "52823629a14dd00c9770fb6ad47dc6310f2c1f60",
"_spec": "merge-stream@^2.0.0",
"_where": "C:\\Users\\thequ\\Documents\\Mynij\\Mynij-unit-tests\\node_modules\\execa",
"author": {
"name": "Stephen Sugden",
"email": "me@stephensugden.com"
},
"bugs": {
"url": "https://github.com/grncdr/merge-stream/issues"
},
"bundleDependencies": false,
"dependencies": {},
"deprecated": false,
"description": "Create a stream that emits events from multiple other streams",
"devDependencies": {
"from2": "^2.0.3",
"istanbul": "^0.4.5"
},
"files": [
"index.js"
],
"homepage": "https://github.com/grncdr/merge-stream#readme",
"license": "MIT",
"name": "merge-stream",
"repository": {
"type": "git",
"url": "git+https://github.com/grncdr/merge-stream.git"
},
"scripts": {
"test": "istanbul cover test.js && istanbul check-cover --statements 100 --branches 100"
},
"version": "2.0.0"
}
declare const mimicFn: {
/**
Make a function mimic another one. It will copy over the properties `name`, `length`, `displayName`, and any custom properties you may have set.
@param to - Mimicking function.
@param from - Function to mimic.
@returns The modified `to` function.
@example
```
import mimicFn = require('mimic-fn');
function foo() {}
foo.unicorn = '🦄';
function wrapper() {
return foo();
}
console.log(wrapper.name);
//=> 'wrapper'
mimicFn(wrapper, foo);
console.log(wrapper.name);
//=> 'foo'
console.log(wrapper.unicorn);
//=> '🦄'
```
*/
<
ArgumentsType extends unknown[],
ReturnType,
FunctionType extends (...arguments: ArgumentsType) => ReturnType
>(
to: (...arguments: ArgumentsType) => ReturnType,
from: FunctionType
): FunctionType;
// TODO: Remove this for the next major release, refactor the whole definition to:
// declare function mimicFn<
// ArgumentsType extends unknown[],
// ReturnType,
// FunctionType extends (...arguments: ArgumentsType) => ReturnType
// >(
// to: (...arguments: ArgumentsType) => ReturnType,
// from: FunctionType
// ): FunctionType;
// export = mimicFn;
default: typeof mimicFn;
};
export = mimicFn;
'use strict';
const mimicFn = (to, from) => {
for (const prop of Reflect.ownKeys(from)) {
Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));
}
return to;
};
module.exports = mimicFn;
// TODO: Remove this for the next major release
module.exports.default = mimicFn;
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.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.
{
"_from": "mimic-fn@^2.1.0",
"_id": "mimic-fn@2.1.0",
"_inBundle": false,
"_integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==",
"_location": "/mimic-fn",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "mimic-fn@^2.1.0",
"name": "mimic-fn",
"escapedName": "mimic-fn",
"rawSpec": "^2.1.0",
"saveSpec": null,
"fetchSpec": "^2.1.0"
},
"_requiredBy": [
"/onetime"
],
"_resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz",
"_shasum": "7ed2c2ccccaf84d3ffcb7a69b57711fc2083401b",
"_spec": "mimic-fn@^2.1.0",
"_where": "C:\\Users\\thequ\\Documents\\Mynij\\Mynij-unit-tests\\node_modules\\onetime",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/mimic-fn/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Make a function mimic another one",
"devDependencies": {
"ava": "^1.4.1",
"tsd": "^0.7.1",
"xo": "^0.24.0"
},
"engines": {
"node": ">=6"
},
"files": [
"index.js",
"index.d.ts"
],
"homepage": "https://github.com/sindresorhus/mimic-fn#readme",
"keywords": [
"function",
"mimic",
"imitate",
"rename",
"copy",
"inherit",
"properties",
"name",
"func",
"fn",
"set",
"infer",
"change"
],
"license": "MIT",
"name": "mimic-fn",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/mimic-fn.git"
},
"scripts": {
"test": "xo && ava && tsd"
},
"version": "2.1.0"
}
# mimic-fn [![Build Status](https://travis-ci.org/sindresorhus/mimic-fn.svg?branch=master)](https://travis-ci.org/sindresorhus/mimic-fn)
> Make a function mimic another one
Useful when you wrap a function in another function and like to preserve the original name and other properties.
## Install
```
$ npm install mimic-fn
```
## Usage
```js
const mimicFn = require('mimic-fn');
function foo() {}
foo.unicorn = '🦄';
function wrapper() {
return foo();
}
console.log(wrapper.name);
//=> 'wrapper'
mimicFn(wrapper, foo);
console.log(wrapper.name);
//=> 'foo'
console.log(wrapper.unicorn);
//=> '🦄'
```
## API
It will copy over the properties `name`, `length`, `displayName`, and any custom properties you may have set.
### mimicFn(to, from)
Modifies the `to` function and returns it.
#### to
Type: `Function`
Mimicking function.
#### from
Type: `Function`
Function to mimic.
## Related
- [rename-fn](https://github.com/sindresorhus/rename-fn) - Rename a function
- [keep-func-props](https://github.com/ehmicky/keep-func-props) - Wrap a function without changing its name, length and other properties
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)
declare namespace npmRunPath {
interface RunPathOptions {
/**
Working directory.
@default process.cwd()
*/
readonly cwd?: string;
/**
PATH to be appended. Default: [`PATH`](https://github.com/sindresorhus/path-key).
Set it to an empty string to exclude the default PATH.
*/
readonly path?: string;
/**
Path to the Node.js executable to use in child processes if that is different from the current one. Its directory is pushed to the front of PATH.
This can be either an absolute path or a path relative to the `cwd` option.
@default process.execPath
*/
readonly execPath?: string;
}
interface ProcessEnv {
[key: string]: string | undefined;
}
interface EnvOptions {
/**
Working directory.
@default process.cwd()
*/
readonly cwd?: string;
/**
Accepts an object of environment variables, like `process.env`, and modifies the PATH using the correct [PATH key](https://github.com/sindresorhus/path-key). Use this if you're modifying the PATH for use in the `child_process` options.
*/
readonly env?: ProcessEnv;
/**
Path to the current Node.js executable. Its directory is pushed to the front of PATH.
This can be either an absolute path or a path relative to the `cwd` option.
@default process.execPath
*/
readonly execPath?: string;
}
}
declare const npmRunPath: {
/**
Get your [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) prepended with locally installed binaries.
@returns The augmented path string.
@example
```
import * as childProcess from 'child_process';
import npmRunPath = require('npm-run-path');
console.log(process.env.PATH);
//=> '/usr/local/bin'
console.log(npmRunPath());
//=> '/Users/sindresorhus/dev/foo/node_modules/.bin:/Users/sindresorhus/dev/node_modules/.bin:/Users/sindresorhus/node_modules/.bin:/Users/node_modules/.bin:/node_modules/.bin:/usr/local/bin'
// `foo` is a locally installed binary
childProcess.execFileSync('foo', {
env: npmRunPath.env()
});
```
*/
(options?: npmRunPath.RunPathOptions): string;
/**
@returns The augmented [`process.env`](https://nodejs.org/api/process.html#process_process_env) object.
*/
env(options?: npmRunPath.EnvOptions): npmRunPath.ProcessEnv;
// TODO: Remove this for the next major release
default: typeof npmRunPath;
};
export = npmRunPath;
'use strict';
const path = require('path');
const pathKey = require('path-key');
const npmRunPath = options => {
options = {
cwd: process.cwd(),
path: process.env[pathKey()],
execPath: process.execPath,
...options
};
let previous;
let cwdPath = path.resolve(options.cwd);
const result = [];
while (previous !== cwdPath) {
result.push(path.join(cwdPath, 'node_modules/.bin'));
previous = cwdPath;
cwdPath = path.resolve(cwdPath, '..');
}
// Ensure the running `node` binary is used
const execPathDir = path.resolve(options.cwd, options.execPath, '..');
result.unshift(execPathDir);
return result.concat(options.path).join(path.delimiter);
};
module.exports = npmRunPath;
// TODO: Remove this for the next major release
module.exports.default = npmRunPath;
module.exports.env = options => {
options = {
env: process.env,
...options
};
const env = {...options.env};
const path = pathKey({env});
options.path = env[path];
env[path] = module.exports(options);
return env;
};
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.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.
{
"_from": "npm-run-path@^4.0.0",
"_id": "npm-run-path@4.0.0",
"_inBundle": false,
"_integrity": "sha512-8eyAOAH+bYXFPSnNnKr3J+yoybe8O87Is5rtAQ8qRczJz1ajcsjg8l2oZqP+Ppx15Ii3S1vUTjQN2h4YO2tWWQ==",
"_location": "/npm-run-path",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "npm-run-path@^4.0.0",
"name": "npm-run-path",
"escapedName": "npm-run-path",
"rawSpec": "^4.0.0",
"saveSpec": null,
"fetchSpec": "^4.0.0"
},
"_requiredBy": [
"/execa"
],
"_resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.0.tgz",
"_shasum": "d644ec1bd0569187d2a52909971023a0a58e8438",
"_spec": "npm-run-path@^4.0.0",
"_where": "C:\\Users\\thequ\\Documents\\Mynij\\Mynij-unit-tests\\node_modules\\execa",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/npm-run-path/issues"
},
"bundleDependencies": false,
"dependencies": {
"path-key": "^3.0.0"
},
"deprecated": false,
"description": "Get your PATH prepended with locally installed binaries",
"devDependencies": {
"ava": "^1.4.1",
"tsd": "^0.7.2",
"xo": "^0.24.0"
},
"engines": {
"node": ">=8"
},
"files": [
"index.js",
"index.d.ts"
],
"homepage": "https://github.com/sindresorhus/npm-run-path#readme",
"keywords": [
"npm",
"run",
"path",
"package",
"bin",
"binary",
"binaries",
"script",
"cli",
"command-line",
"execute",
"executable"
],
"license": "MIT",
"name": "npm-run-path",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/npm-run-path.git"
},
"scripts": {
"test": "xo && ava && tsd"
},
"version": "4.0.0"
}
# npm-run-path [![Build Status](https://travis-ci.org/sindresorhus/npm-run-path.svg?branch=master)](https://travis-ci.org/sindresorhus/npm-run-path)
> Get your [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) prepended with locally installed binaries
In [npm run scripts](https://docs.npmjs.com/cli/run-script) you can execute locally installed binaries by name. This enables the same outside npm.
## Install
```
$ npm install npm-run-path
```
## Usage
```js
const childProcess = require('child_process');
const npmRunPath = require('npm-run-path');
console.log(process.env.PATH);
//=> '/usr/local/bin'
console.log(npmRunPath());
//=> '/Users/sindresorhus/dev/foo/node_modules/.bin:/Users/sindresorhus/dev/node_modules/.bin:/Users/sindresorhus/node_modules/.bin:/Users/node_modules/.bin:/node_modules/.bin:/usr/local/bin'
// `foo` is a locally installed binary
childProcess.execFileSync('foo', {
env: npmRunPath.env()
});
```
## API
### npmRunPath(options?)
Returns the augmented path string.
#### options
Type: `object`
##### cwd
Type: `string`<br>
Default: `process.cwd()`
Working directory.
##### path
Type: `string`<br>
Default: [`PATH`](https://github.com/sindresorhus/path-key)
PATH to be appended.<br>
Set it to an empty string to exclude the default PATH.
##### execPath
Type: `string`<br>
Default: `process.execPath`
Path to the current Node.js executable. Its directory is pushed to the front of PATH.
This can be either an absolute path or a path relative to the [`cwd` option](#cwd).
### npmRunPath.env(options?)
Returns the augmented [`process.env`](https://nodejs.org/api/process.html#process_process_env) object.
#### options
Type: `object`
##### cwd
Type: `string`<br>
Default: `process.cwd()`
Working directory.
##### env
Type: `Object`
Accepts an object of environment variables, like `process.env`, and modifies the PATH using the correct [PATH key](https://github.com/sindresorhus/path-key). Use this if you're modifying the PATH for use in the `child_process` options.
##### execPath
Type: `string`<br>
Default: `process.execPath`
Path to the Node.js executable to use in child processes if that is different from the current one. Its directory is pushed to the front of PATH.
This can be either an absolute path or a path relative to the [`cwd` option](#cwd).
## Related
- [npm-run-path-cli](https://github.com/sindresorhus/npm-run-path-cli) - CLI for this module
- [execa](https://github.com/sindresorhus/execa) - Execute a locally installed binary
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-npm-run-path?utm_source=npm-npm-run-path&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>
declare namespace oneTime {
interface Options {
/**
Throw an error when called more than once.
@default false
*/
throw?: boolean;
}
}
declare const oneTime: {
/**
Ensure a function is only called once. When called multiple times it will return the return value from the first call.
@param fn - Function that should only be called once.
@returns A function that only calls `fn` once.
*/
<ArgumentsType extends unknown[], ReturnType>(
fn: (...arguments: ArgumentsType) => ReturnType,
options?: oneTime.Options
): (...arguments: ArgumentsType) => ReturnType;
/**
Get the number of times `fn` has been called.
@param fn - Function to get call count from.
@returns A number representing how many times `fn` has been called.
@example
```
import onetime = require('onetime');
const foo = onetime(() => {});
foo();
foo();
foo();
console.log(onetime.callCount(foo));
//=> 3
```
*/
callCount(fn: (...arguments: any[]) => unknown): number;
// TODO: Remove this for the next major release
default: typeof oneTime;
};
export = oneTime;
'use strict';
const mimicFn = require('mimic-fn');
const calledFunctions = new WeakMap();
const oneTime = (fn, options = {}) => {
if (typeof fn !== 'function') {
throw new TypeError('Expected a function');
}
let ret;
let isCalled = false;
let callCount = 0;
const functionName = fn.displayName || fn.name || '<anonymous>';
const onetime = function (...args) {
calledFunctions.set(onetime, ++callCount);
if (isCalled) {
if (options.throw === true) {
throw new Error(`Function \`${functionName}\` can only be called once`);
}
return ret;
}
isCalled = true;
ret = fn.apply(this, args);
fn = null;
return ret;
};
mimicFn(onetime, fn);
calledFunctions.set(onetime, callCount);
return onetime;
};
module.exports = oneTime;
// TODO: Remove this for the next major release
module.exports.default = oneTime;
module.exports.callCount = fn => {
if (!calledFunctions.has(fn)) {
throw new Error(`The given function \`${fn.name}\` is not wrapped by the \`onetime\` package`);
}
return calledFunctions.get(fn);
};
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.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.
{
"_from": "onetime@^5.1.0",
"_id": "onetime@5.1.0",
"_inBundle": false,
"_integrity": "sha512-5NcSkPHhwTVFIQN+TUqXoS5+dlElHXdpAWu9I0HP20YOtIi+aZ0Ct82jdlILDxjLEAWwvm+qj1m6aEtsDVmm6Q==",
"_location": "/onetime",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "onetime@^5.1.0",
"name": "onetime",
"escapedName": "onetime",
"rawSpec": "^5.1.0",
"saveSpec": null,
"fetchSpec": "^5.1.0"
},
"_requiredBy": [
"/execa"
],
"_resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.0.tgz",
"_shasum": "fff0f3c91617fe62bb50189636e99ac8a6df7be5",
"_spec": "onetime@^5.1.0",
"_where": "C:\\Users\\thequ\\Documents\\Mynij\\Mynij-unit-tests\\node_modules\\execa",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/onetime/issues"
},
"bundleDependencies": false,
"dependencies": {
"mimic-fn": "^2.1.0"
},
"deprecated": false,
"description": "Ensure a function is only called once",
"devDependencies": {
"ava": "^1.4.1",
"tsd": "^0.7.1",
"xo": "^0.24.0"
},
"engines": {
"node": ">=6"
},
"files": [
"index.js",
"index.d.ts"
],
"homepage": "https://github.com/sindresorhus/onetime#readme",
"keywords": [
"once",
"function",
"one",
"onetime",
"func",
"fn",
"single",
"call",
"called",
"prevent"
],
"license": "MIT",
"name": "onetime",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/onetime.git"
},
"scripts": {
"test": "xo && ava && tsd"
},
"version": "5.1.0"
}
# onetime [![Build Status](https://travis-ci.org/sindresorhus/onetime.svg?branch=master)](https://travis-ci.org/sindresorhus/onetime)
> Ensure a function is only called once
When called multiple times it will return the return value from the first call.
*Unlike the module [once](https://github.com/isaacs/once), this one isn't naughty and extending `Function.prototype`.*
## Install
```
$ npm install onetime
```
## Usage
```js
const onetime = require('onetime');
let i = 0;
const foo = onetime(() => ++i);
foo(); //=> 0
foo(); //=> 0
foo(); //=> 0
onetime.callCount(foo); //=> 3
```
```js
const onetime = require('onetime');
const foo = onetime(() => {}, {throw: true});
foo();
foo();
//=> Error: Function `foo` can only be called once
```
## API
### onetime(fn, [options])
Returns a function that only calls `fn` once.
#### fn
Type: `Function`
Function that should only be called once.
#### options
Type: `Object`
##### throw
Type: `boolean`<br>
Default: `false`
Throw an error when called more than once.
### onetime.callCount(fn)
Returns a number representing how many times `fn` has been called.
Note: It throws an error if you pass in a function that is not wrapped by `onetime`.
```js
const foo = onetime(() => {});
foo();
foo();
foo();
console.log(onetime.callCount(foo));
//=> 3
```
#### fn
Type: `Function`
Function to get call count from.
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)
'use strict';
module.exports = async (
promise,
onFinally = (() => {})
) => {
let value;
try {
value = await promise;
} catch (error) {
await onFinally();
throw error;
}
await onFinally();
return value;
};
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.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.
{
"_from": "p-finally@^2.0.0",
"_id": "p-finally@2.0.1",
"_inBundle": false,
"_integrity": "sha512-vpm09aKwq6H9phqRQzecoDpD8TmVyGw70qmWlyq5onxY7tqyTTFVvxMykxQSQKILBSFlbXpypIw2T1Ml7+DDtw==",
"_location": "/p-finally",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "p-finally@^2.0.0",
"name": "p-finally",
"escapedName": "p-finally",
"rawSpec": "^2.0.0",
"saveSpec": null,
"fetchSpec": "^2.0.0"
},
"_requiredBy": [
"/execa"
],
"_resolved": "https://registry.npmjs.org/p-finally/-/p-finally-2.0.1.tgz",
"_shasum": "bd6fcaa9c559a096b680806f4d657b3f0f240561",
"_spec": "p-finally@^2.0.0",
"_where": "C:\\Users\\thequ\\Documents\\Mynij\\Mynij-unit-tests\\node_modules\\execa",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/p-finally/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "`Promise#finally()` ponyfill - Invoked when the promise is settled regardless of outcome",
"devDependencies": {
"ava": "^1.4.1",
"xo": "^0.24.0"
},
"engines": {
"node": ">=8"
},
"files": [
"index.js"
],
"homepage": "https://github.com/sindresorhus/p-finally#readme",
"keywords": [
"promise",
"finally",
"handler",
"function",
"async",
"await",
"promises",
"settled",
"ponyfill",
"polyfill",
"shim",
"bluebird"
],
"license": "MIT",
"name": "p-finally",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/p-finally.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "2.0.1"
}
# p-finally [![Build Status](https://travis-ci.org/sindresorhus/p-finally.svg?branch=master)](https://travis-ci.org/sindresorhus/p-finally)
> [`Promise#finally()`](https://github.com/tc39/proposal-promise-finally) [ponyfill](https://ponyfill.com) - Invoked when the promise is settled regardless of outcome
Useful for cleanup.
## Install
```
$ npm install p-finally
```
## Usage
```js
const pFinally = require('p-finally');
const directory = createTempDirectory();
(async () => {
await pFinally(write(directory), () => {
cleanup(directory);
});
});
```
## API
### pFinally(promise, onFinally?)
Returns a `Promise`.
#### onFinally
Type: `Function`
Note: Throwing or returning a rejected promise will reject `promise` with the rejection reason.
## Related
- [p-try](https://github.com/sindresorhus/p-try) - `Promise.try()` ponyfill - Starts a promise chain
- [More…](https://github.com/sindresorhus/promise-fun)
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-p-finally?utm_source=npm-p-finally&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>
/// <reference types="node" />
declare namespace pathKey {
interface Options {
/**
Use a custom environment variables object. Default: [`process.env`](https://nodejs.org/api/process.html#process_process_env).
*/
readonly env?: {[key: string]: string | undefined};
/**
Get the PATH key for a specific platform. Default: [`process.platform`](https://nodejs.org/api/process.html#process_process_platform).
*/
readonly platform?: NodeJS.Platform;
}
}
declare const pathKey: {
/**
Get the [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) environment variable key cross-platform.
@example
```
import pathKey = require('path-key');
const key = pathKey();
//=> 'PATH'
const PATH = process.env[key];
//=> '/usr/local/bin:/usr/bin:/bin'
```
*/
(options?: pathKey.Options): string;
// TODO: Remove this for the next major release, refactor the whole definition to:
// declare function pathKey(options?: pathKey.Options): string;
// export = pathKey;
default: typeof pathKey;
};
export = pathKey;
'use strict';
const pathKey = (options = {}) => {
const environment = options.env || process.env;
const platform = options.platform || process.platform;
if (platform !== 'win32') {
return 'PATH';
}
return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';
};
module.exports = pathKey;
// TODO: Remove this for the next major release
module.exports.default = pathKey;
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.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.
{
"_from": "path-key@^3.1.0",
"_id": "path-key@3.1.1",
"_inBundle": false,
"_integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
"_location": "/path-key",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "path-key@^3.1.0",
"name": "path-key",
"escapedName": "path-key",
"rawSpec": "^3.1.0",
"saveSpec": null,
"fetchSpec": "^3.1.0"
},
"_requiredBy": [
"/cross-spawn",
"/npm-run-path"
],
"_resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
"_shasum": "581f6ade658cbba65a0d3380de7753295054f375",
"_spec": "path-key@^3.1.0",
"_where": "C:\\Users\\thequ\\Documents\\Mynij\\Mynij-unit-tests\\node_modules\\cross-spawn",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/path-key/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Get the PATH environment variable key cross-platform",
"devDependencies": {
"@types/node": "^11.13.0",
"ava": "^1.4.1",
"tsd": "^0.7.2",
"xo": "^0.24.0"
},
"engines": {
"node": ">=8"
},
"files": [
"index.js",
"index.d.ts"
],
"homepage": "https://github.com/sindresorhus/path-key#readme",
"keywords": [
"path",
"key",
"environment",
"env",
"variable",
"var",
"get",
"cross-platform",
"windows"
],
"license": "MIT",
"name": "path-key",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/path-key.git"
},
"scripts": {
"test": "xo && ava && tsd"
},
"version": "3.1.1"
}
# path-key [![Build Status](https://travis-ci.org/sindresorhus/path-key.svg?branch=master)](https://travis-ci.org/sindresorhus/path-key)
> Get the [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) environment variable key cross-platform
It's usually `PATH`, but on Windows it can be any casing like `Path`...
## Install
```
$ npm install path-key
```
## Usage
```js
const pathKey = require('path-key');
const key = pathKey();
//=> 'PATH'
const PATH = process.env[key];
//=> '/usr/local/bin:/usr/bin:/bin'
```
## API
### pathKey(options?)
#### options
Type: `object`
##### env
Type: `object`<br>
Default: [`process.env`](https://nodejs.org/api/process.html#process_process_env)
Use a custom environment variables object.
#### platform
Type: `string`<br>
Default: [`process.platform`](https://nodejs.org/api/process.html#process_process_platform)
Get the PATH key for a specific platform.
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-path-key?utm_source=npm-path-key&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>
language: node_js
node_js:
- "0.10"
script: "npm test"
The MIT License (MIT)
Copyright (c) 2014 Mathias Buus
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
# pump
pump is a small node module that pipes streams together and destroys all of them if one of them closes.
```
npm install pump
```
[![build status](http://img.shields.io/travis/mafintosh/pump.svg?style=flat)](http://travis-ci.org/mafintosh/pump)
## What problem does it solve?
When using standard `source.pipe(dest)` source will _not_ be destroyed if dest emits close or an error.
You are also not able to provide a callback to tell when then pipe has finished.
pump does these two things for you
## Usage
Simply pass the streams you want to pipe together to pump and add an optional callback
``` js
var pump = require('pump')
var fs = require('fs')
var source = fs.createReadStream('/dev/random')
var dest = fs.createWriteStream('/dev/null')
pump(source, dest, function(err) {
console.log('pipe finished', err)
})
setTimeout(function() {
dest.destroy() // when dest is closed pump will destroy source
}, 1000)
```
You can use pump to pipe more than two streams together as well
``` js
var transform = someTransformStream()
pump(source, transform, anotherTransform, dest, function(err) {
console.log('pipe finished', err)
})
```
If `source`, `transform`, `anotherTransform` or `dest` closes all of them will be destroyed.
Similarly to `stream.pipe()`, `pump()` returns the last stream passed in, so you can do:
```
return pump(s1, s2) // returns s2
```
If you want to return a stream that combines *both* s1 and s2 to a single stream use
[pumpify](https://github.com/mafintosh/pumpify) instead.
## License
MIT
## Related
`pump` is part of the [mississippi stream utility collection](https://github.com/maxogden/mississippi) which includes more useful stream modules similar to this one.
var once = require('once')
var eos = require('end-of-stream')
var fs = require('fs') // we only need fs to get the ReadStream and WriteStream prototypes
var noop = function () {}
var ancient = /^v?\.0/.test(process.version)
var isFn = function (fn) {
return typeof fn === 'function'
}
var isFS = function (stream) {
if (!ancient) return false // newer node version do not need to care about fs is a special way
if (!fs) return false // browser
return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close)
}
var isRequest = function (stream) {
return stream.setHeader && isFn(stream.abort)
}
var destroyer = function (stream, reading, writing, callback) {
callback = once(callback)
var closed = false
stream.on('close', function () {
closed = true
})
eos(stream, {readable: reading, writable: writing}, function (err) {
if (err) return callback(err)
closed = true
callback()
})
var destroyed = false
return function (err) {
if (closed) return
if (destroyed) return
destroyed = true
if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks
if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want
if (isFn(stream.destroy)) return stream.destroy()
callback(err || new Error('stream was destroyed'))
}
}
var call = function (fn) {
fn()
}
var pipe = function (from, to) {
return from.pipe(to)
}
var pump = function () {
var streams = Array.prototype.slice.call(arguments)
var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop
if (Array.isArray(streams[0])) streams = streams[0]
if (streams.length < 2) throw new Error('pump requires two streams per minimum')
var error
var destroys = streams.map(function (stream, i) {
var reading = i < streams.length - 1
var writing = i > 0
return destroyer(stream, reading, writing, function (err) {
if (!error) error = err
if (err) destroys.forEach(call)
if (reading) return
destroys.forEach(call)
callback(error)
})
})
return streams.reduce(pipe)
}
module.exports = pump
{
"_from": "pump@^3.0.0",
"_id": "pump@3.0.0",
"_inBundle": false,
"_integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==",
"_location": "/pump",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "pump@^3.0.0",
"name": "pump",
"escapedName": "pump",
"rawSpec": "^3.0.0",
"saveSpec": null,
"fetchSpec": "^3.0.0"
},
"_requiredBy": [
"/get-stream"
],
"_resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz",
"_shasum": "b4a2116815bde2f4e1ea602354e8c75565107a64",
"_spec": "pump@^3.0.0",
"_where": "C:\\Users\\thequ\\Documents\\Mynij\\Mynij-unit-tests\\node_modules\\get-stream",
"author": {
"name": "Mathias Buus Madsen",
"email": "mathiasbuus@gmail.com"
},
"browser": {
"fs": false
},
"bugs": {
"url": "https://github.com/mafintosh/pump/issues"
},
"bundleDependencies": false,
"dependencies": {
"end-of-stream": "^1.1.0",
"once": "^1.3.1"
},
"deprecated": false,
"description": "pipe streams together and close all of them if one of them closes",
"homepage": "https://github.com/mafintosh/pump#readme",
"keywords": [
"streams",
"pipe",
"destroy",
"callback"
],
"license": "MIT",
"name": "pump",
"repository": {
"type": "git",
"url": "git://github.com/mafintosh/pump.git"
},
"scripts": {
"test": "node test-browser.js && node test-node.js"
},
"version": "3.0.0"
}
var stream = require('stream')
var pump = require('./index')
var rs = new stream.Readable()
var ws = new stream.Writable()
rs._read = function (size) {
this.push(Buffer(size).fill('abc'))
}
ws._write = function (chunk, encoding, cb) {
setTimeout(function () {
cb()
}, 100)
}
var toHex = function () {
var reverse = new (require('stream').Transform)()
reverse._transform = function (chunk, enc, callback) {
reverse.push(chunk.toString('hex'))
callback()
}
return reverse
}
var wsClosed = false
var rsClosed = false
var callbackCalled = false
var check = function () {
if (wsClosed && rsClosed && callbackCalled) {
console.log('test-browser.js passes')
clearTimeout(timeout)
}
}
ws.on('finish', function () {
wsClosed = true
check()
})
rs.on('end', function () {
rsClosed = true
check()
})
var res = pump(rs, toHex(), toHex(), toHex(), ws, function () {
callbackCalled = true
check()
})
if (res !== ws) {
throw new Error('should return last stream')
}
setTimeout(function () {
rs.push(null)
rs.emit('close')
}, 1000)
var timeout = setTimeout(function () {
check()
throw new Error('timeout')
}, 5000)
var pump = require('./index')
var rs = require('fs').createReadStream('/dev/random')
var ws = require('fs').createWriteStream('/dev/null')
var toHex = function () {
var reverse = new (require('stream').Transform)()
reverse._transform = function (chunk, enc, callback) {
reverse.push(chunk.toString('hex'))
callback()
}
return reverse
}
var wsClosed = false
var rsClosed = false
var callbackCalled = false
var check = function () {
if (wsClosed && rsClosed && callbackCalled) {
console.log('test-node.js passes')
clearTimeout(timeout)
}
}
ws.on('close', function () {
wsClosed = true
check()
})
rs.on('close', function () {
rsClosed = true
check()
})
var res = pump(rs, toHex(), toHex(), toHex(), ws, function () {
callbackCalled = true
check()
})
if (res !== ws) {
throw new Error('should return last stream')
}
setTimeout(function () {
rs.destroy()
}, 1000)
var timeout = setTimeout(function () {
throw new Error('timeout')
}, 5000)
'use strict';
const shebangRegex = require('shebang-regex');
module.exports = (string = '') => {
const match = string.match(shebangRegex);
if (!match) {
return null;
}
const [path, argument] = match[0].replace(/#! ?/, '').split(' ');
const binary = path.split('/').pop();
if (binary === 'env') {
return argument;
}
return argument ? `${binary} ${argument}` : binary;
};
MIT License
Copyright (c) Kevin Mårtensson <kevinmartensson@gmail.com> (github.com/kevva)
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.
{
"_from": "shebang-command@^2.0.0",
"_id": "shebang-command@2.0.0",
"_inBundle": false,
"_integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
"_location": "/shebang-command",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "shebang-command@^2.0.0",
"name": "shebang-command",
"escapedName": "shebang-command",
"rawSpec": "^2.0.0",
"saveSpec": null,
"fetchSpec": "^2.0.0"
},
"_requiredBy": [
"/cross-spawn"
],
"_resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
"_shasum": "ccd0af4f8835fbdc265b82461aaf0c36663f34ea",
"_spec": "shebang-command@^2.0.0",
"_where": "C:\\Users\\thequ\\Documents\\Mynij\\Mynij-unit-tests\\node_modules\\cross-spawn",
"author": {
"name": "Kevin Mårtensson",
"email": "kevinmartensson@gmail.com",
"url": "github.com/kevva"
},
"bugs": {
"url": "https://github.com/kevva/shebang-command/issues"
},
"bundleDependencies": false,
"dependencies": {
"shebang-regex": "^3.0.0"
},
"deprecated": false,
"description": "Get the command from a shebang",
"devDependencies": {
"ava": "^2.3.0",
"xo": "^0.24.0"
},
"engines": {
"node": ">=8"
},
"files": [
"index.js"
],
"homepage": "https://github.com/kevva/shebang-command#readme",
"keywords": [
"cmd",
"command",
"parse",
"shebang"
],
"license": "MIT",
"name": "shebang-command",
"repository": {
"type": "git",
"url": "git+https://github.com/kevva/shebang-command.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "2.0.0"
}
# shebang-command [![Build Status](https://travis-ci.org/kevva/shebang-command.svg?branch=master)](https://travis-ci.org/kevva/shebang-command)
> Get the command from a shebang
## Install
```
$ npm install shebang-command
```
## Usage
```js
const shebangCommand = require('shebang-command');
shebangCommand('#!/usr/bin/env node');
//=> 'node'
shebangCommand('#!/bin/bash');
//=> 'bash'
```
## API
### shebangCommand(string)
#### string
Type: `string`
String containing a shebang.
/**
Regular expression for matching a [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) line.
@example
```
import shebangRegex = require('shebang-regex');
const string = '#!/usr/bin/env node\nconsole.log("unicorns");';
shebangRegex.test(string);
//=> true
shebangRegex.exec(string)[0];
//=> '#!/usr/bin/env node'
shebangRegex.exec(string)[1];
//=> '/usr/bin/env node'
```
*/
declare const shebangRegex: RegExp;
export = shebangRegex;
'use strict';
module.exports = /^#!(.*)/;
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.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.
{
"_from": "shebang-regex@^3.0.0",
"_id": "shebang-regex@3.0.0",
"_inBundle": false,
"_integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
"_location": "/shebang-regex",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "shebang-regex@^3.0.0",
"name": "shebang-regex",
"escapedName": "shebang-regex",
"rawSpec": "^3.0.0",
"saveSpec": null,
"fetchSpec": "^3.0.0"
},
"_requiredBy": [
"/shebang-command"
],
"_resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
"_shasum": "ae16f1644d873ecad843b0307b143362d4c42172",
"_spec": "shebang-regex@^3.0.0",
"_where": "C:\\Users\\thequ\\Documents\\Mynij\\Mynij-unit-tests\\node_modules\\shebang-command",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/shebang-regex/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Regular expression for matching a shebang line",
"devDependencies": {
"ava": "^1.4.1",
"tsd": "^0.7.2",
"xo": "^0.24.0"
},
"engines": {
"node": ">=8"
},
"files": [
"index.js",
"index.d.ts"
],
"homepage": "https://github.com/sindresorhus/shebang-regex#readme",
"keywords": [
"regex",
"regexp",
"shebang",
"match",
"test",
"line"
],
"license": "MIT",
"name": "shebang-regex",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/shebang-regex.git"
},
"scripts": {
"test": "xo && ava && tsd"
},
"version": "3.0.0"
}
# shebang-regex [![Build Status](https://travis-ci.org/sindresorhus/shebang-regex.svg?branch=master)](https://travis-ci.org/sindresorhus/shebang-regex)
> Regular expression for matching a [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) line
## Install
```
$ npm install shebang-regex
```
## Usage
```js
const shebangRegex = require('shebang-regex');
const string = '#!/usr/bin/env node\nconsole.log("unicorns");';
shebangRegex.test(string);
//=> true
shebangRegex.exec(string)[0];
//=> '#!/usr/bin/env node'
shebangRegex.exec(string)[1];
//=> '/usr/bin/env node'
```
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)
# Change Log
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
<a name="3.0.1"></a>
## [3.0.1](https://github.com/tapjs/signal-exit/compare/v3.0.0...v3.0.1) (2016-09-08)
### Bug Fixes
* do not listen on SIGBUS, SIGFPE, SIGSEGV and SIGILL ([#40](https://github.com/tapjs/signal-exit/issues/40)) ([5b105fb](https://github.com/tapjs/signal-exit/commit/5b105fb))
<a name="3.0.0"></a>
# [3.0.0](https://github.com/tapjs/signal-exit/compare/v2.1.2...v3.0.0) (2016-06-13)
### Bug Fixes
* get our test suite running on Windows ([#23](https://github.com/tapjs/signal-exit/issues/23)) ([6f3eda8](https://github.com/tapjs/signal-exit/commit/6f3eda8))
* hooking SIGPROF was interfering with profilers see [#21](https://github.com/tapjs/signal-exit/issues/21) ([#24](https://github.com/tapjs/signal-exit/issues/24)) ([1248a4c](https://github.com/tapjs/signal-exit/commit/1248a4c))
### BREAKING CHANGES
* signal-exit no longer wires into SIGPROF
The ISC License
Copyright (c) 2015, Contributors
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice
appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE
LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
# signal-exit
[![Build Status](https://travis-ci.org/tapjs/signal-exit.png)](https://travis-ci.org/tapjs/signal-exit)
[![Coverage](https://coveralls.io/repos/tapjs/signal-exit/badge.svg?branch=master)](https://coveralls.io/r/tapjs/signal-exit?branch=master)
[![NPM version](https://img.shields.io/npm/v/signal-exit.svg)](https://www.npmjs.com/package/signal-exit)
[![Windows Tests](https://img.shields.io/appveyor/ci/bcoe/signal-exit/master.svg?label=Windows%20Tests)](https://ci.appveyor.com/project/bcoe/signal-exit)
[![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version)
When you want to fire an event no matter how a process exits:
* reaching the end of execution.
* explicitly having `process.exit(code)` called.
* having `process.kill(pid, sig)` called.
* receiving a fatal signal from outside the process
Use `signal-exit`.
```js
var onExit = require('signal-exit')
onExit(function (code, signal) {
console.log('process exited!')
})
```
## API
`var remove = onExit(function (code, signal) {}, options)`
The return value of the function is a function that will remove the
handler.
Note that the function *only* fires for signals if the signal would
cause the proces to exit. That is, there are no other listeners, and
it is a fatal signal.
## Options
* `alwaysLast`: Run this handler after any other signal or exit
handlers. This causes `process.emit` to be monkeypatched.
// Note: since nyc uses this module to output coverage, any lines
// that are in the direct sync flow of nyc's outputCoverage are
// ignored, since we can never get coverage for them.
var assert = require('assert')
var signals = require('./signals.js')
var EE = require('events')
/* istanbul ignore if */
if (typeof EE !== 'function') {
EE = EE.EventEmitter
}
var emitter
if (process.__signal_exit_emitter__) {
emitter = process.__signal_exit_emitter__
} else {
emitter = process.__signal_exit_emitter__ = new EE()
emitter.count = 0
emitter.emitted = {}
}
// Because this emitter is a global, we have to check to see if a
// previous version of this library failed to enable infinite listeners.
// I know what you're about to say. But literally everything about
// signal-exit is a compromise with evil. Get used to it.
if (!emitter.infinite) {
emitter.setMaxListeners(Infinity)
emitter.infinite = true
}
module.exports = function (cb, opts) {
assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler')
if (loaded === false) {
load()
}
var ev = 'exit'
if (opts && opts.alwaysLast) {
ev = 'afterexit'
}
var remove = function () {
emitter.removeListener(ev, cb)
if (emitter.listeners('exit').length === 0 &&
emitter.listeners('afterexit').length === 0) {
unload()
}
}
emitter.on(ev, cb)
return remove
}
module.exports.unload = unload
function unload () {
if (!loaded) {
return
}
loaded = false
signals.forEach(function (sig) {
try {
process.removeListener(sig, sigListeners[sig])
} catch (er) {}
})
process.emit = originalProcessEmit
process.reallyExit = originalProcessReallyExit
emitter.count -= 1
}
function emit (event, code, signal) {
if (emitter.emitted[event]) {
return
}
emitter.emitted[event] = true
emitter.emit(event, code, signal)
}
// { <signal>: <listener fn>, ... }
var sigListeners = {}
signals.forEach(function (sig) {
sigListeners[sig] = function listener () {
// If there are no other listeners, an exit is coming!
// Simplest way: remove us and then re-send the signal.
// We know that this will kill the process, so we can
// safely emit now.
var listeners = process.listeners(sig)
if (listeners.length === emitter.count) {
unload()
emit('exit', null, sig)
/* istanbul ignore next */
emit('afterexit', null, sig)
/* istanbul ignore next */
process.kill(process.pid, sig)
}
}
})
module.exports.signals = function () {
return signals
}
module.exports.load = load
var loaded = false
function load () {
if (loaded) {
return
}
loaded = true
// This is the number of onSignalExit's that are in play.
// It's important so that we can count the correct number of
// listeners on signals, and don't wait for the other one to
// handle it instead of us.
emitter.count += 1
signals = signals.filter(function (sig) {
try {
process.on(sig, sigListeners[sig])
return true
} catch (er) {
return false
}
})
process.emit = processEmit
process.reallyExit = processReallyExit
}
var originalProcessReallyExit = process.reallyExit
function processReallyExit (code) {
process.exitCode = code || 0
emit('exit', process.exitCode, null)
/* istanbul ignore next */
emit('afterexit', process.exitCode, null)
/* istanbul ignore next */
originalProcessReallyExit.call(process, process.exitCode)
}
var originalProcessEmit = process.emit
function processEmit (ev, arg) {
if (ev === 'exit') {
if (arg !== undefined) {
process.exitCode = arg
}
var ret = originalProcessEmit.apply(this, arguments)
emit('exit', process.exitCode, null)
/* istanbul ignore next */
emit('afterexit', process.exitCode, null)
return ret
} else {
return originalProcessEmit.apply(this, arguments)
}
}
{
"_from": "signal-exit@^3.0.2",
"_id": "signal-exit@3.0.2",
"_inBundle": false,
"_integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=",
"_location": "/signal-exit",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "signal-exit@^3.0.2",
"name": "signal-exit",
"escapedName": "signal-exit",
"rawSpec": "^3.0.2",
"saveSpec": null,
"fetchSpec": "^3.0.2"
},
"_requiredBy": [
"/execa"
],
"_resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz",
"_shasum": "b5fdc08f1287ea1178628e415e25132b73646c6d",
"_spec": "signal-exit@^3.0.2",
"_where": "C:\\Users\\thequ\\Documents\\Mynij\\Mynij-unit-tests\\node_modules\\execa",
"author": {
"name": "Ben Coe",
"email": "ben@npmjs.com"
},
"bugs": {
"url": "https://github.com/tapjs/signal-exit/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "when you want to fire an event no matter how a process exits.",
"devDependencies": {
"chai": "^3.5.0",
"coveralls": "^2.11.10",
"nyc": "^8.1.0",
"standard": "^7.1.2",
"standard-version": "^2.3.0",
"tap": "^8.0.1"
},
"files": [
"index.js",
"signals.js"
],
"homepage": "https://github.com/tapjs/signal-exit",
"keywords": [
"signal",
"exit"
],
"license": "ISC",
"main": "index.js",
"name": "signal-exit",
"repository": {
"type": "git",
"url": "git+https://github.com/tapjs/signal-exit.git"
},
"scripts": {
"coverage": "nyc report --reporter=text-lcov | coveralls",
"pretest": "standard",
"release": "standard-version",
"test": "tap --timeout=240 ./test/*.js --cov"
},
"version": "3.0.2"
}
// This is not the set of all possible signals.
//
// It IS, however, the set of all signals that trigger
// an exit on either Linux or BSD systems. Linux is a
// superset of the signal names supported on BSD, and
// the unknown signals just fail to register, so we can
// catch that easily enough.
//
// Don't bother with SIGKILL. It's uncatchable, which
// means that we can't fire any callbacks anyway.
//
// If a user does happen to register a handler on a non-
// fatal signal like SIGWINCH or something, and then
// exit, it'll end up firing `process.emit('exit')`, so
// the handler will be fired anyway.
//
// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
// artificially, inherently leave the process in a
// state from which it is not safe to try and enter JS
// listeners.
module.exports = [
'SIGABRT',
'SIGALRM',
'SIGHUP',
'SIGINT',
'SIGTERM'
]
if (process.platform !== 'win32') {
module.exports.push(
'SIGVTALRM',
'SIGXCPU',
'SIGXFSZ',
'SIGUSR2',
'SIGTRAP',
'SIGSYS',
'SIGQUIT',
'SIGIOT'
// should detect profiler and enable/disable accordingly.
// see #21
// 'SIGPROF'
)
}
if (process.platform === 'linux') {
module.exports.push(
'SIGIO',
'SIGPOLL',
'SIGPWR',
'SIGSTKFLT',
'SIGUNUSED'
)
}
'use strict';
module.exports = input => {
const LF = typeof input === 'string' ? '\n' : '\n'.charCodeAt();
const CR = typeof input === 'string' ? '\r' : '\r'.charCodeAt();
if (input[input.length - 1] === LF) {
input = input.slice(0, input.length - 1);
}
if (input[input.length - 1] === CR) {
input = input.slice(0, input.length - 1);
}
return input;
};
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.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.
{
"_from": "strip-final-newline@^2.0.0",
"_id": "strip-final-newline@2.0.0",
"_inBundle": false,
"_integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==",
"_location": "/strip-final-newline",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "strip-final-newline@^2.0.0",
"name": "strip-final-newline",
"escapedName": "strip-final-newline",
"rawSpec": "^2.0.0",
"saveSpec": null,
"fetchSpec": "^2.0.0"
},
"_requiredBy": [
"/execa"
],
"_resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz",
"_shasum": "89b852fb2fcbe936f6f4b3187afb0a12c1ab58ad",
"_spec": "strip-final-newline@^2.0.0",
"_where": "C:\\Users\\thequ\\Documents\\Mynij\\Mynij-unit-tests\\node_modules\\execa",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/strip-final-newline/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Strip the final newline character from a string/buffer",
"devDependencies": {
"ava": "^0.25.0",
"xo": "^0.23.0"
},
"engines": {
"node": ">=6"
},
"files": [
"index.js"
],
"homepage": "https://github.com/sindresorhus/strip-final-newline#readme",
"keywords": [
"strip",
"trim",
"remove",
"delete",
"final",
"last",
"end",
"file",
"newline",
"linebreak",
"character",
"string",
"buffer"
],
"license": "MIT",
"name": "strip-final-newline",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/strip-final-newline.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "2.0.0"
}
# strip-final-newline [![Build Status](https://travis-ci.com/sindresorhus/strip-final-newline.svg?branch=master)](https://travis-ci.com/sindresorhus/strip-final-newline)
> Strip the final [newline character](https://en.wikipedia.org/wiki/Newline) from a string/buffer
Can be useful when parsing the output of, for example, `ChildProcess#execFile`, as [binaries usually output a newline at the end](https://stackoverflow.com/questions/729692/why-should-text-files-end-with-a-newline). Normally, you would use `stdout.trim()`, but that would also remove newlines at the start and whitespace.
## Install
```
$ npm install strip-final-newline
```
## Usage
```js
const stripFinalNewline = require('strip-final-newline');
stripFinalNewline('foo\nbar\n\n');
//=> 'foo\nbar\n'
stripFinalNewline(Buffer.from('foo\nbar\n\n')).toString();
//=> 'foo\nbar\n'
```
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)
# Changes
## 2.0.2
* Rename bin to `node-which`
## 2.0.1
* generate changelog and publish on version bump
* enforce 100% test coverage
* Promise interface
## 2.0.0
* Parallel tests, modern JavaScript, and drop support for node < 8
## 1.3.1
* update deps
* update travis
## v1.3.0
* Add nothrow option to which.sync
* update tap
## v1.2.14
* appveyor: drop node 5 and 0.x
* travis-ci: add node 6, drop 0.x
## v1.2.13
* test: Pass missing option to pass on windows
* update tap
* update isexe to 2.0.0
* neveragain.tech pledge request
## v1.2.12
* Removed unused require
## v1.2.11
* Prevent changelog script from being included in package
## v1.2.10
* Use env.PATH only, not env.Path
## v1.2.9
* fix for paths starting with ../
* Remove unused `is-absolute` module
## v1.2.8
* bullet items in changelog that contain (but don't start with) #
## v1.2.7
* strip 'update changelog' changelog entries out of changelog
## v1.2.6
* make the changelog bulleted
## v1.2.5
* make a changelog, and keep it up to date
* don't include tests in package
* Properly handle relative-path executables
* appveyor
* Attach error code to Not Found error
* Make tests pass on Windows
## v1.2.4
* Fix typo
## v1.2.3
* update isexe, fix regression in pathExt handling
## v1.2.2
* update deps, use isexe module, test windows
## v1.2.1
* Sometimes windows PATH entries are quoted
* Fixed a bug in the check for group and user mode bits. This bug was introduced during refactoring for supporting strict mode.
* doc cli
## v1.2.0
* Add support for opt.all and -as cli flags
* test the bin
* update travis
* Allow checking for multiple programs in bin/which
* tap 2
## v1.1.2
* travis
* Refactored and fixed undefined error on Windows
* Support strict mode
## v1.1.1
* test +g exes against secondary groups, if available
* Use windows exe semantics on cygwin & msys
* cwd should be first in path on win32, not last
* Handle lower-case 'env.Path' on Windows
* Update docs
* use single-quotes
## v1.1.0
* Add tests, depend on is-absolute
## v1.0.9
* which.js: root is allowed to execute files owned by anyone
## v1.0.8
* don't use graceful-fs
## v1.0.7
* add license to package.json
## v1.0.6
* isc license
## 1.0.5
* Awful typo
## 1.0.4
* Test for path absoluteness properly
* win: Allow '' as a pathext if cmd has a . in it
## 1.0.3
* Remove references to execPath
* Make `which.sync()` work on Windows by honoring the PATHEXT variable.
* Make `isExe()` always return true on Windows.
* MIT
## 1.0.2
* Only files can be exes
## 1.0.1
* Respect the PATHEXT env for win32 support
* should 0755 the bin
* binary
* guts
* package
* 1st
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
# which
Like the unix `which` utility.
Finds the first instance of a specified executable in the PATH
environment variable. Does not cache the results, so `hash -r` is not
needed when the PATH changes.
## USAGE
```javascript
var which = require('which')
// async usage
which('node', function (er, resolvedPath) {
// er is returned if no "node" is found on the PATH
// if it is found, then the absolute path to the exec is returned
})
// or promise
which('node').then(resolvedPath => { ... }).catch(er => { ... not found ... })
// sync usage
// throws if not found
var resolved = which.sync('node')
// if nothrow option is used, returns null if not found
resolved = which.sync('node', {nothrow: true})
// Pass options to override the PATH and PATHEXT environment vars.
which('node', { path: someOtherPath }, function (er, resolved) {
if (er)
throw er
console.log('found at %j', resolved)
})
```
## CLI USAGE
Same as the BSD `which(1)` binary.
```
usage: which [-as] program ...
```
## OPTIONS
You may pass an options object as the second argument.
- `path`: Use instead of the `PATH` environment variable.
- `pathExt`: Use instead of the `PATHEXT` environment variable.
- `all`: Return all matches, instead of just the first one. Note that
this means the function returns an array of strings instead of a
single string.
#!/usr/bin/env node
var which = require("../")
if (process.argv.length < 3)
usage()
function usage () {
console.error('usage: which [-as] program ...')
process.exit(1)
}
var all = false
var silent = false
var dashdash = false
var args = process.argv.slice(2).filter(function (arg) {
if (dashdash || !/^-/.test(arg))
return true
if (arg === '--') {
dashdash = true
return false
}
var flags = arg.substr(1).split('')
for (var f = 0; f < flags.length; f++) {
var flag = flags[f]
switch (flag) {
case 's':
silent = true
break
case 'a':
all = true
break
default:
console.error('which: illegal option -- ' + flag)
usage()
}
}
return false
})
process.exit(args.reduce(function (pv, current) {
try {
var f = which.sync(current, { all: all })
if (all)
f = f.join('\n')
if (!silent)
console.log(f)
return pv;
} catch (e) {
return 1;
}
}, 0))
{
"_from": "which@^2.0.1",
"_id": "which@2.0.2",
"_inBundle": false,
"_integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
"_location": "/which",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "which@^2.0.1",
"name": "which",
"escapedName": "which",
"rawSpec": "^2.0.1",
"saveSpec": null,
"fetchSpec": "^2.0.1"
},
"_requiredBy": [
"/cross-spawn"
],
"_resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
"_shasum": "7c6a8dd0a636a0327e10b59c9286eee93f3f51b1",
"_spec": "which@^2.0.1",
"_where": "C:\\Users\\thequ\\Documents\\Mynij\\Mynij-unit-tests\\node_modules\\cross-spawn",
"author": {
"name": "Isaac Z. Schlueter",
"email": "i@izs.me",
"url": "http://blog.izs.me"
},
"bin": {
"node-which": "./bin/node-which"
},
"bugs": {
"url": "https://github.com/isaacs/node-which/issues"
},
"bundleDependencies": false,
"dependencies": {
"isexe": "^2.0.0"
},
"deprecated": false,
"description": "Like which(1) unix command. Find the first instance of an executable in the PATH.",
"devDependencies": {
"mkdirp": "^0.5.0",
"rimraf": "^2.6.2",
"tap": "^14.6.9"
},
"engines": {
"node": ">= 8"
},
"files": [
"which.js",
"bin/node-which"
],
"homepage": "https://github.com/isaacs/node-which#readme",
"license": "ISC",
"main": "which.js",
"name": "which",
"repository": {
"type": "git",
"url": "git://github.com/isaacs/node-which.git"
},
"scripts": {
"changelog": "git add CHANGELOG.md",
"postchangelog": "git commit -m 'update changelog - '${npm_package_version}",
"postpublish": "git push origin --follow-tags",
"postversion": "npm publish",
"prechangelog": "bash gen-changelog.sh",
"prepublish": "npm run changelog",
"preversion": "npm test",
"test": "tap"
},
"tap": {
"check-coverage": true
},
"version": "2.0.2"
}
const isWindows = process.platform === 'win32' ||
process.env.OSTYPE === 'cygwin' ||
process.env.OSTYPE === 'msys'
const path = require('path')
const COLON = isWindows ? ';' : ':'
const isexe = require('isexe')
const getNotFoundError = (cmd) =>
Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' })
const getPathInfo = (cmd, opt) => {
const colon = opt.colon || COLON
// If it has a slash, then we don't bother searching the pathenv.
// just check the file itself, and that's it.
const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? ['']
: (
[
// windows always checks the cwd first
...(isWindows ? [process.cwd()] : []),
...(opt.path || process.env.PATH ||
/* istanbul ignore next: very unusual */ '').split(colon),
]
)
const pathExtExe = isWindows
? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'
: ''
const pathExt = isWindows ? pathExtExe.split(colon) : ['']
if (isWindows) {
if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')
pathExt.unshift('')
}
return {
pathEnv,
pathExt,
pathExtExe,
}
}
const which = (cmd, opt, cb) => {
if (typeof opt === 'function') {
cb = opt
opt = {}
}
if (!opt)
opt = {}
const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)
const found = []
const step = i => new Promise((resolve, reject) => {
if (i === pathEnv.length)
return opt.all && found.length ? resolve(found)
: reject(getNotFoundError(cmd))
const ppRaw = pathEnv[i]
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw
const pCmd = path.join(pathPart, cmd)
const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
: pCmd
resolve(subStep(p, i, 0))
})
const subStep = (p, i, ii) => new Promise((resolve, reject) => {
if (ii === pathExt.length)
return resolve(step(i + 1))
const ext = pathExt[ii]
isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
if (!er && is) {
if (opt.all)
found.push(p + ext)
else
return resolve(p + ext)
}
return resolve(subStep(p, i, ii + 1))
})
})
return cb ? step(0).then(res => cb(null, res), cb) : step(0)
}
const whichSync = (cmd, opt) => {
opt = opt || {}
const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)
const found = []
for (let i = 0; i < pathEnv.length; i ++) {
const ppRaw = pathEnv[i]
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw
const pCmd = path.join(pathPart, cmd)
const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
: pCmd
for (let j = 0; j < pathExt.length; j ++) {
const cur = p + pathExt[j]
try {
const is = isexe.sync(cur, { pathExt: pathExtExe })
if (is) {
if (opt.all)
found.push(cur)
else
return cur
}
} catch (ex) {}
}
}
if (opt.all && found.length)
return found
if (opt.nothrow)
return null
throw getNotFoundError(cmd)
}
module.exports = which
which.sync = whichSync
......@@ -101,6 +101,16 @@
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",
"integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac="
},
"cross-spawn": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.1.tgz",
"integrity": "sha512-u7v4o84SwFpD32Z8IIcPZ6z1/ie24O6RU3RbtL5Y316l3KuHVPx9ItBgWQ6VlfAFnRnTtMUrsQ9MUUTuEZjogg==",
"requires": {
"path-key": "^3.1.0",
"shebang-command": "^2.0.0",
"which": "^2.0.1"
}
},
"debug": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz",
......@@ -119,6 +129,14 @@
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz",
"integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA=="
},
"end-of-stream": {
"version": "1.4.4",
"resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz",
"integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==",
"requires": {
"once": "^1.4.0"
}
},
"es6-promise": {
"version": "4.2.8",
"resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.2.8.tgz",
......@@ -132,6 +150,23 @@
"es6-promise": "^4.0.3"
}
},
"execa": {
"version": "3.4.0",
"resolved": "https://registry.npmjs.org/execa/-/execa-3.4.0.tgz",
"integrity": "sha512-r9vdGQk4bmCuK1yKQu1KTwcT2zwfWdbdaXfCtAh+5nU/4fSX+JAb7vZGvI5naJrQlvONrEB20jeruESI69530g==",
"requires": {
"cross-spawn": "^7.0.0",
"get-stream": "^5.0.0",
"human-signals": "^1.1.1",
"is-stream": "^2.0.0",
"merge-stream": "^2.0.0",
"npm-run-path": "^4.0.0",
"onetime": "^5.1.0",
"p-finally": "^2.0.0",
"signal-exit": "^3.0.2",
"strip-final-newline": "^2.0.0"
}
},
"extract-zip": {
"version": "1.6.7",
"resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-1.6.7.tgz",
......@@ -192,6 +227,14 @@
"type-fest": "^0.3.0"
}
},
"get-stream": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.1.0.tgz",
"integrity": "sha512-EXr1FOzrzTfGeL0gQdeFEvOMm2mzMOglyiOXSTpPC+iAjAKftbr3jpCMWynogwYnM+eSj9sHGc6wjIcDvYiygw==",
"requires": {
"pump": "^3.0.0"
}
},
"glob": {
"version": "7.1.4",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz",
......@@ -224,6 +267,11 @@
}
}
},
"human-signals": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/human-signals/-/human-signals-1.1.1.tgz",
"integrity": "sha512-SEQu7vl8KjNL2eoGBLF3+wAjpsNfA9XMlXAYj/3EdaNfAlxKthD1xjEQfGOUhllCGGJVNY34bRr6lPINhNjyZw=="
},
"inflight": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
......@@ -243,11 +291,21 @@
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz",
"integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8="
},
"is-stream": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.0.tgz",
"integrity": "sha512-XCoy+WlUr7d1+Z8GgSuXmpuUFC9fOhRXglJMx+dwLKTkL44Cjd4W1Z5P+BQZpr+cR93aGP4S/s7Ftw6Nd/kiEw=="
},
"isarray": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
"integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE="
},
"isexe": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
"integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA="
},
"locate-path": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz",
......@@ -257,11 +315,21 @@
"path-exists": "^3.0.0"
}
},
"merge-stream": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",
"integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w=="
},
"mime": {
"version": "2.4.4",
"resolved": "https://registry.npmjs.org/mime/-/mime-2.4.4.tgz",
"integrity": "sha512-LRxmNwziLPT828z+4YkNzloCFC2YM4wrB99k+AV5ZbEyfGNWfG8SO1FUXLmLDBSo89NrJZ4DIWeLjy1CHGhMGA=="
},
"mimic-fn": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz",
"integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg=="
},
"minimatch": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz",
......@@ -288,6 +356,14 @@
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
},
"npm-run-path": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.0.tgz",
"integrity": "sha512-8eyAOAH+bYXFPSnNnKr3J+yoybe8O87Is5rtAQ8qRczJz1ajcsjg8l2oZqP+Ppx15Ii3S1vUTjQN2h4YO2tWWQ==",
"requires": {
"path-key": "^3.0.0"
}
},
"once": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
......@@ -296,6 +372,19 @@
"wrappy": "1"
}
},
"onetime": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.0.tgz",
"integrity": "sha512-5NcSkPHhwTVFIQN+TUqXoS5+dlElHXdpAWu9I0HP20YOtIi+aZ0Ct82jdlILDxjLEAWwvm+qj1m6aEtsDVmm6Q==",
"requires": {
"mimic-fn": "^2.1.0"
}
},
"p-finally": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/p-finally/-/p-finally-2.0.1.tgz",
"integrity": "sha512-vpm09aKwq6H9phqRQzecoDpD8TmVyGw70qmWlyq5onxY7tqyTTFVvxMykxQSQKILBSFlbXpypIw2T1Ml7+DDtw=="
},
"p-limit": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.1.tgz",
......@@ -327,6 +416,11 @@
"resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
"integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18="
},
"path-key": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
"integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="
},
"pend": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz",
......@@ -347,6 +441,15 @@
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.0.0.tgz",
"integrity": "sha1-M8UDmPcOp+uW0h97gXYwpVeRx+4="
},
"pump": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz",
"integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==",
"requires": {
"end-of-stream": "^1.1.0",
"once": "^1.3.1"
}
},
"puppeteer": {
"version": "1.20.0",
"resolved": "https://registry.npmjs.org/puppeteer/-/puppeteer-1.20.0.tgz",
......@@ -412,6 +515,24 @@
"resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz",
"integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc="
},
"shebang-command": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
"integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
"requires": {
"shebang-regex": "^3.0.0"
}
},
"shebang-regex": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
"integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="
},
"signal-exit": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz",
"integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0="
},
"string-width": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz",
......@@ -438,6 +559,11 @@
"ansi-regex": "^4.1.0"
}
},
"strip-final-newline": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz",
"integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA=="
},
"systeminformation": {
"version": "4.14.17",
"resolved": "https://registry.npmjs.org/systeminformation/-/systeminformation-4.14.17.tgz",
......@@ -466,6 +592,14 @@
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8="
},
"which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
"integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
"requires": {
"isexe": "^2.0.0"
}
},
"which-module": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz",
......
......@@ -46,6 +46,11 @@ function runScriptSync(list, callback) {
var err = code === 0 ? null : new Error('exit code ' + code);
callback(err);
});
setTimeout(() => {
stream.write(items + ",Timeout error" + "\n");
process.kill();
return;
}, 7200000); //2 hours
}
fs.truncateSync("./results/rss.csv");
......
......@@ -27,6 +27,11 @@ function runScriptSync(list, callback) {
var err = code === 0 ? null : new Error('exit code ' + code);
callback(err);
});
setTimeout(() => {
stream.write(items + ",Timeout error" + "\n");
process.kill();
return;
}, 7200000); //2 hours
}
fs.truncateSync("./results/sitemap.csv");
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment