Capturing stdout/ stderr in Node.js using Domain module

This weekend I am working on a project that enables Applaudience developers to test multiple data aggregation scripts in parallel. Implementing this functionality requires that a single API endpoint evaluates multiple user submitted scripts. However, if either script fails, we need to retrieve the logs of the execution too, i.e. we need to capture what was written to stdout.

Image for post
Image for post
Capturing Node.js stdout and stderr output into a variable.
let output = '';

const originalStdoutWrite = process.stdout.write.bind(process.stdout);

process.stdout.write = (chunk, encoding, callback) => {
if (typeof chunk === 'string') {
output += chunk;
}

return originalStdoutWrite(chunk, encoding, callback);
};

console.log('foo');
console.log('bar');
console.log('baz');

process.stdout.write = originalStdoutWrite;
console.log('qux');output;
const createDomain = require('domain').create;const originalStdoutWrite = process.stdout.write.bind(process.stdout);process.stdout.write = (chunk, encoding, callback) => {
if (
process.domain &&
process.domain.outputInterceptor !== undefined &&
typeof chunk === 'string'
) {
process.domain.outputInterceptor += chunk;
}
return originalStdoutWrite(chunk, encoding, callback);
};
const captureStdout = async (routine) => {
const domain = createDomain();
domain.outputInterceptor = ''; await domain.run(() => {
return routine();
});
const output = domain.outputInterceptor; domain.outputInterceptor = undefined; domain.exit(); return output;
};

A notice about “deprecation”

Several people commented that domain module is deprecated and it should not be used.

Image for post
Image for post
Deprecation notice

Written by

Software architect, startup adviser. Editor of https://medium.com/applaudience. Founder of https://go2cinema.com.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store