Intercepts stdout/ stderr.
This module uses domain
to capture asynchronous function output.
Read Capturing stdout/ stderr in Node.js using Domain module.
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();
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
.
/**
* @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;