|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +// This implements a light-weight printer that writes to stdout/stderr |
| 4 | +// directly to avoid the overhead in the console abstraction. |
| 5 | + |
| 6 | +const { formatWithOptions } = require('internal/util/inspect'); |
| 7 | +const { writeString } = internalBinding('fs'); |
| 8 | +const { handleErrorFromBinding } = require('internal/fs/utils'); |
| 9 | +const { guessHandleType } = internalBinding('util'); |
| 10 | +const { log } = require('internal/console/global'); |
| 11 | + |
| 12 | +const kStdout = 1; |
| 13 | +const kStderr = 2; |
| 14 | +const handleType = [undefined, undefined, undefined]; |
| 15 | +function getFdType(fd) { |
| 16 | + if (handleType[fd] === undefined) { |
| 17 | + handleType[fd] = guessHandleType(fd); |
| 18 | + } |
| 19 | + return handleType[fd]; |
| 20 | +} |
| 21 | + |
| 22 | +function formatAndWrite(fd, obj, ignoreErrors, colors = false) { |
| 23 | + const str = `${formatWithOptions({ colors }, obj)}\n`; |
| 24 | + const ctx = {}; |
| 25 | + writeString(fd, str, null, undefined, undefined, ctx); |
| 26 | + if (!ignoreErrors) { |
| 27 | + handleErrorFromBinding(ctx); |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +let colors; |
| 32 | +function getColors() { |
| 33 | + if (colors === undefined) { |
| 34 | + colors = require('internal/tty').getColorDepth() > 2; |
| 35 | + } |
| 36 | + return colors; |
| 37 | +} |
| 38 | + |
| 39 | +// TODO(joyeecheung): replace more internal process._rawDebug() |
| 40 | +// and console.log() usage with this if possible. |
| 41 | +function print(fd, obj, ignoreErrors = true) { |
| 42 | + switch (getFdType(fd)) { |
| 43 | + case 'TTY': |
| 44 | + formatAndWrite(fd, obj, ignoreErrors, getColors()); |
| 45 | + break; |
| 46 | + case 'FILE': |
| 47 | + formatAndWrite(fd, obj, ignoreErrors); |
| 48 | + break; |
| 49 | + case 'PIPE': |
| 50 | + case 'TCP': |
| 51 | + // Fallback to console.log to handle IPC. |
| 52 | + if (process.channel && process.channel.fd === fd) { |
| 53 | + log(obj); |
| 54 | + } else { |
| 55 | + formatAndWrite(fd, obj, ignoreErrors); |
| 56 | + } |
| 57 | + break; |
| 58 | + default: |
| 59 | + log(obj); |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +module.exports = { |
| 64 | + print, |
| 65 | + kStderr, |
| 66 | + kStdout |
| 67 | +}; |
0 commit comments