1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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
};
|