March 15, 2020

Debug when stdout and stderr not available

I am developing a blessed application and outputting to standard output and error stream messes up the terminal for obvious reasons.

This is my solution for this problem.

/* eslint-disable no-console */
import { Console } from 'console';
import * as fs from 'fs';
import * as path from 'path';

const output = fs.createWriteStream(
  path.resolve(__dirname, '../stdout.log')
);
const errorOutput = fs.createWriteStream(
  path.resolve(__dirname, '../stderr.log'),
);

// Custom simple logger
export const debug = new Console({
  stdout: output,
  stderr: errorOutput,
  colorMode: true,
});

console.log = debug.log;
console.info = debug.info;
console.error = debug.error;

I have created a new console instance and piping the stdout and stderr to 2 different files.

By changing the reference of console.log to debug.log, we are able to send the streams to the files specified.

So if we or any other module uses console.log or indirectly writes to the stdout or stderr, then we’ll get those stream written to our files.

For checking out the stdout and stderr I open 2 instances of terminal and run these 2 commands in each:

tail -f stdout.log

tail -f stderr.log
node.js javascript
March 15, 2020

Typescript function parameter Types

Defining a wrapper function with the same parameters as the inner function.

import { spawn } from 'child_process';

function customSpawn(...options: Parameters<typeof spawn>) {
  console.log('some custom code');
  
  return spawn(...options);
}

References:

typescript