Skip to content

gajus/output-interceptor

Repository files navigation

output-interceptor

GitSpo Mentions Travis build status Coveralls NPM version Canonical Code Style Twitter Follow

Intercepts stdout/ stderr.

Implementation

This module uses domain to capture asynchronous function output.

Read Capturing stdout/ stderr in Node.js using Domain module.

Usage

import {
  createOutputInterceptor
} from 'output-interceptor';

const interceptOutput = createOutputInterceptor();

const main = async () => {
  const result = await interceptOutput(() => {
    console.log('foo');
    console.error('bar');

    return Promise.resolve('baz');
  });

  result === 'baz';

  interceptOutput.output === 'foo\nbar\n';
};

main();

Singleton or dependency injection pattern

It is recommended that you only create one instance of output-interceptor per entire project, e.g.

Create ./routines.js file with contents:

import {
  createOutputInterceptor
} from 'output-interceptor';

export const interceptOutput = createOutputInterceptor();

Then just import the {interceptOutput} routine from elsewhere in your codebase.

Alternatively, create an instance of output-interceptor at the top of the program and pass it down using dependency injection.

The benefit of this approach is that you do not create unnecessary wrappers around process.stderr.write and process.stdout.write.

API

/**
 * @property interceptStderr Default: true.
 * @property interceptStdout Default: true.
 * @property stripAnsi Default: true.
 */
export type OutputInterceptorUserConfigurationType = {|
  +interceptStderr?: boolean,
  +interceptStdout?: boolean,
  +stripAnsi?: boolean
|};

/**
 * @returns Intercepted output.
 */
type FlushType = () => string;

/**
 * @property output Output produced during the executing of the `routine`.
 */
export type OutputInterceptorType = {|
  <T>(routine: () => Promise<T> | T): Promise<T>,
  output: ''
|};

createOutputInterceptor(userConfiguration?: OutputInterceptorUserConfigurationType): OutputInterceptorType;