2016-09-24 81 views
2

我正在使用Node.js v5.8.0。爲什麼`(console.error = console.trace)();`在Node.js中使'堆內存不足'?

我想使console.error工作爲console.trace,所以我用console.error = console.trace;。但是,當我打電話給console.error,發生致命內存錯誤:

<--- Last few GCs ---> 

    29296 ms: Mark-sweep 1328.1 (1403.1) -> 1328.1 (1404.1) MB, 32.8/0.0 ms [allocation failure] [GC in old space requested]. 
    29314 ms: Mark-sweep 1328.1 (1404.1) -> 1328.1 (1404.1) MB, 17.8/0.0 ms [allocation failure] [GC in old space requested]. 
    29333 ms: Mark-sweep 1328.1 (1404.1) -> 1338.8 (1403.1) MB, 19.7/0.0 ms [last resort gc]. 
    29353 ms: Mark-sweep 1338.8 (1403.1) -> 1349.7 (1403.1) MB, 19.3/0.0 ms [last resort gc]. 


<--- JS stacktrace ---> 

==== JS stack trace ========================================= 

Security context: 00000318EFDCFB61 <JS Object> 
    1: DoJoin(aka DoJoin) [native array.js:~129] [pc=00000130FFFB1B73] (this=00000318EFD04381 <undefined>,w=000001FBBADF90E1 <JS Array[17]>,x=17,N=00000318EFD043C1 <true>,J=000003D7BECEC771 <String[1]\: \n>,I=00000318EFDB46F1 <JS Function ConvertToString (SharedFunctionInfo 00000318EFD52DC9)>) 
    2: Join(aka Join) [native array.js:180] [pc=00000130FFF08772] (this=00000318EFD04381 <undefined>... 

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory 

是什麼原因? console.trace是否在內部調用console.error

回答

5

在NodeJS中,console.errorconsole.warn用於打印到標準錯誤輸出。 console.trace在內部使用console.error打印到標準錯誤輸出,因爲console.trace經常用於出錯。

這裏是到console.trace調用console.error行的鏈接: https://github.com/nodejs/node/blob/1c84579031e34326742c9c264f54625c5918197c/lib/console.js#L89

你可以試試這個代碼:

console.trace = function trace() { 
    var err = new Error(); 
    err.name = 'Trace'; 
    err.message = util.format.apply(null, arguments); 
    Error.captureStackTrace(err, trace); 
    this.oldWarn(err.stack); 
}; 

console.oldWarn = console.warn; 
console.error = console.warn = console.trace;