process: add --redirect-warnings command line argument · nodejs/node@16802c0
@@ -4,10 +4,81 @@ const traceWarnings = process.traceProcessWarnings;
44const noDeprecation = process.noDeprecation;
55const traceDeprecation = process.traceDeprecation;
66const throwDeprecation = process.throwDeprecation;
7+const config = process.binding('config');
78const prefix = `(${process.release.name}:${process.pid}) `;
89910exports.setup = setupProcessWarnings;
101112+var fs;
13+var cachedFd;
14+var acquiringFd = false;
15+function nop() {}
16+17+function lazyFs() {
18+if (!fs)
19+fs = require('fs');
20+return fs;
21+}
22+23+function writeOut(message) {
24+if (console && typeof console.error === 'function')
25+return console.error(message);
26+process._rawDebug(message);
27+}
28+29+function onClose(fd) {
30+return function() {
31+lazyFs().close(fd, nop);
32+};
33+}
34+35+function onOpen(cb) {
36+return function(err, fd) {
37+acquiringFd = false;
38+if (fd !== undefined) {
39+cachedFd = fd;
40+process.on('exit', onClose(fd));
41+}
42+cb(err, fd);
43+process.emit('_node_warning_fd_acquired', err, fd);
44+};
45+}
46+47+function onAcquired(message) {
48+// make a best effort attempt at writing the message
49+// to the fd. Errors are ignored at this point.
50+return function(err, fd) {
51+if (err)
52+return writeOut(message);
53+lazyFs().appendFile(fd, `${message}\n`, nop);
54+};
55+}
56+57+function acquireFd(cb) {
58+if (cachedFd === undefined && !acquiringFd) {
59+acquiringFd = true;
60+lazyFs().open(config.warningFile, 'a', onOpen(cb));
61+} else if (cachedFd !== undefined && !acquiringFd) {
62+cb(null, cachedFd);
63+} else {
64+process.once('_node_warning_fd_acquired', cb);
65+}
66+}
67+68+function output(message) {
69+if (typeof config.warningFile === 'string') {
70+acquireFd(onAcquired(message));
71+return;
72+}
73+writeOut(message);
74+}
75+76+function doEmitWarning(warning) {
77+return function() {
78+process.emit('warning', warning);
79+};
80+}
81+1182function setupProcessWarnings() {
1283if (!process.noProcessWarnings && process.env.NODE_NO_WARNINGS !== '1') {
1384process.on('warning', (warning) => {
@@ -21,7 +92,7 @@ function setupProcessWarnings() {
2192var toString = warning.toString;
2293if (typeof toString !== 'function')
2394toString = Error.prototype.toString;
24-console.error(`${prefix}${toString.apply(warning)}`);
95+output(`${prefix}${toString.apply(warning)}`);
2596}
2697});
2798}
@@ -44,6 +115,6 @@ function setupProcessWarnings() {
44115if (throwDeprecation && warning.name === 'DeprecationWarning')
45116throw warning;
46117else
47-process.nextTick(() => process.emit('warning', warning));
118+process.nextTick(doEmitWarning(warning));
48119};
49120}