node js stderr/stdout



  • // tslint:disable: only-arrow-functions
    // https://gist.github.com/pguillory/729616

    import path from 'path'
    const appRootDir = require('app-root-dir').get()

    export const hook_stdout = () => {
    const target: string = path.join(appRootDir, 'logstd.txt')
    const log_file = require('fs').createWriteStream(target, { flags: 'w' })

    function hook_stream(stream, callback) {
    const old_write = stream.write

    stream.write = (function(write) {
      return function(string, encoding, fd) {
        write.apply(stream, arguments) // comments this line if you don't want output in the console
        callback(string, encoding, fd)
      }
    })(stream.write)
    
    return function() {
      stream.write = old_write
    }
    

    }

    const unhook_stdout = hook_stream(process.stdout, function(str, encoding, fd) {
    log_file.write(str, encoding)
    })

    const unhook_stderr = hook_stream(process.stderr, function(str, encoding, fd) {
    log_file.write(str, encoding)
    })

    return {
    unhook_stdout,
    unhook_stderr,
    }
    }


Log in to reply