symfony-style-console
Version:
Use the style and utilities of the Symfony Console in Node.js
108 lines (107 loc) • 2.75 kB
JavaScript
import { VERBOSITY_NORMAL } from './OutputInterface';
import StreamOutput from './StreamOutput';
/**
* `ConsoleOutput` is the default class for all CLI output. It uses `stdout` and `stderr`.
*
* This class is a convenient wrapper around [[StreamOutput]] for both `stdout` and `stderr`.
*
* ```
* const output = new ConsoleOutput()
* ```
*
* This is equivalent to:
*
* ```
* const output = new StreamOutput(process.stdout)
* const stdErr = new StreamOutput(process.stderr)
* ```
*
* @author Fabien Potencier <fabien@symfony.com>
*
* Original PHP class
*
* @author Florian Reuschel <florian@loilo.de>
*
* Port to TypeScript
*
*/
export default class ConsoleOutput extends StreamOutput {
constructor(verbosity = VERBOSITY_NORMAL, output = process.stdout, decorated = true, formatter = null) {
super(output, verbosity, decorated, formatter);
const actualDecorated = this.isDecorated();
this.stderr = new StreamOutput(this.openErrorStream(), verbosity, decorated, formatter);
if (null === decorated) {
this.setDecorated(actualDecorated && this.stderr.isDecorated());
}
}
/**
* {@inheritdoc}
*/
setDecorated(decorated) {
super.setDecorated(decorated);
this.stderr.setDecorated(decorated);
}
/**
* {@inheritdoc}
*/
setFormatter(formatter) {
super.setFormatter(formatter);
this.stderr.setFormatter(formatter);
}
/**
* {@inheritdoc}
*/
setVerbosity(level) {
super.setVerbosity(level);
this.stderr.setVerbosity(level);
}
/**
* {@inheritdoc}
*/
getErrorOutput() {
return this.stderr;
}
/**
* {@inheritdoc}
*/
setErrorOutput(error) {
this.stderr = error;
}
/**
* Returns true if current environment supports writing console output to STDOUT.
*
* @return bool
*/
hasStdoutSupport() {
return !!process.stdout;
}
/**
* Returns true if current environment supports writing console output to STDERR.
*
* @return bool
*/
hasStderrSupport() {
return !!process.stderr;
}
/**
* @return NodeJS.WritableStream
*/
openOutputStream() {
if (!this.hasStdoutSupport()) {
throw new Error('No process.stdout available');
}
return process.stdout;
}
/**
* @return resource
*/
openErrorStream() {
if (!this.hasStderrSupport()) {
if (!this.hasStdoutSupport()) {
throw new Error('Neither process.stderr nor process.stdout available');
}
return process.stdout;
}
return process.stderr;
}
}