diff options
author | Joyee Cheung <joyeec9h3@gmail.com> | 2019-04-18 12:25:57 +0800 |
---|---|---|
committer | Joyee Cheung <joyeec9h3@gmail.com> | 2019-04-28 14:46:23 +0800 |
commit | 2b24ffae2240163a74ae11e49ee198e98abb07dc (patch) | |
tree | f6abfd48eba3b21e722dd96e0ede245d50d28035 /lib/internal/util | |
parent | 31b3dd28429df7ea7ebc84bdfaf8d9eb9e417b41 (diff) | |
download | android-node-v8-2b24ffae2240163a74ae11e49ee198e98abb07dc.tar.gz android-node-v8-2b24ffae2240163a74ae11e49ee198e98abb07dc.tar.bz2 android-node-v8-2b24ffae2240163a74ae11e49ee198e98abb07dc.zip |
lib: print to stdout/stderr directly instead of using console
This patch adds an internal function that prints to stdout or
stderr by directly writing to the known file descriptor, and
uses it internally in common cases to avoid the overhead
of the console implementation.
PR-URL: https://github.com/nodejs/node/pull/27320
Reviewed-By: James M Snell <jasnell@gmail.com>
Diffstat (limited to 'lib/internal/util')
-rw-r--r-- | lib/internal/util/print.js | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/lib/internal/util/print.js b/lib/internal/util/print.js new file mode 100644 index 0000000000..4c9327502e --- /dev/null +++ b/lib/internal/util/print.js @@ -0,0 +1,67 @@ +'use strict'; + +// This implements a light-weight printer that writes to stdout/stderr +// directly to avoid the overhead in the console abstraction. + +const { formatWithOptions } = require('internal/util/inspect'); +const { writeString } = internalBinding('fs'); +const { handleErrorFromBinding } = require('internal/fs/utils'); +const { guessHandleType } = internalBinding('util'); +const { log } = require('internal/console/global'); + +const kStdout = 1; +const kStderr = 2; +const handleType = [undefined, undefined, undefined]; +function getFdType(fd) { + if (handleType[fd] === undefined) { + handleType[fd] = guessHandleType(fd); + } + return handleType[fd]; +} + +function formatAndWrite(fd, obj, ignoreErrors, colors = false) { + const str = `${formatWithOptions({ colors }, obj)}\n`; + const ctx = {}; + writeString(fd, str, null, undefined, undefined, ctx); + if (!ignoreErrors) { + handleErrorFromBinding(ctx); + } +} + +let colors; +function getColors() { + if (colors === undefined) { + colors = require('internal/tty').getColorDepth() > 2; + } + return colors; +} + +// TODO(joyeecheung): replace more internal process._rawDebug() +// and console.log() usage with this if possible. +function print(fd, obj, ignoreErrors = true) { + switch (getFdType(fd)) { + case 'TTY': + formatAndWrite(fd, obj, ignoreErrors, getColors()); + break; + case 'FILE': + formatAndWrite(fd, obj, ignoreErrors); + break; + case 'PIPE': + case 'TCP': + // Fallback to console.log to handle IPC. + if (process.channel && process.channel.fd === fd) { + log(obj); + } else { + formatAndWrite(fd, obj, ignoreErrors); + } + break; + default: + log(obj); + } +} + +module.exports = { + print, + kStderr, + kStdout +}; |