尽pipe使用err.stack,但是在“Error(native)”而不是实际的node.js stacktrace上

在Windows 10的io.js 3.2.0 64bit中使用以下示例代码,并使用node example.js调用以下代码

 'use strict'; const fs = require('fs'); fs.readdir('I_DONT_EXIST', function (/**Error*/ err, /**string[]*/ files) { if (err) { console.log(err.stack); } }); 

我明白了

 { [Error: ENOENT: no such file or directory, scandir '...\I_DONT_EXIST'] errno: -4058, code: 'ENOENT', syscall: 'scandir', path: '...\\I_DONT_EXIST' } Error: ENOENT: no such file or directory, scandir '...\I_DONT_EXIST' at Error (native) 

所以我得到at Error (native)而不是实际的错误跟踪,即使我要求err.stack

这不应该是实际的堆栈跟踪?

编辑:

下面是一小段代码,演示了我对最后(第三)评论的答案。

 'use strict'; const fs = require('fs'); fs.readdir('I_DONT_EXIST', function (/**Error*/ err, /**string[]*/ files) { if (err) { console.log('\n== 1) Original error'); console.log(JSON.stringify(err, Reflect.ownKeys(err), 4)); console.log('\n== 2) Original error "stack" property'); console.log(err.stack); const e = new Error(err); // Copy parameters I'm interested in from the original object e.code = err.code; console.log('\n\n== 3) New error'); console.log(JSON.stringify(e, Reflect.ownKeys(e), 4)); console.log('\n== 4) New error "stack" property'); console.log(e.stack); console.log('\n\n== 5) Throw the error'); throw e; } }); 

我得到的输出结果显示,当我检查原来的错误对象,但是在新的错误对象中得到一个错误对象时,我甚至没有得到错误最终出现位置的文件位置:

 == 1) Original error { "stack": "Error: ENOENT: no such file or directory, scandir 'C:\\Users\\xxx\\I_DONT_EXIST'", "message": "ENOENT: no such file or directory, scandir 'C:\\Users\\xxx\\I_DONT_EXIST'", "errno": -4058, "code": "ENOENT", "syscall": "scandir", "path": "C:\\Users\\xxx\\I_DONT_EXIST" } == 2) Original error "stack" property Error: ENOENT: no such file or directory, scandir 'C:\Users\xxx\I_DONT_EXIST' == 3) New error { "stack": "Error: Error: ENOENT: no such file or directory, scandir 'C:\\Users\\xxx\\I_DONT_EXIST'\n at C:\\Users\\xxx\\test.js:11:19", "message": "Error: ENOENT: no such file or directory, scandir 'C:\\Users\\xxx\\I_DONT_EXIST'", "code": "ENOENT" } == 4) New error "stack" property Error: Error: ENOENT: no such file or directory, scandir 'C:\Users\xxx\I_DONT_EXIST' at C:\Users\xxx\test.js:11:19 == 5) Throw the error C:\Users\xxx\test.js:20 throw e; ^ Error: Error: ENOENT: no such file or directory, scandir 'C:\Users\xxx\I_DONT_EXIST' at C:\Users\xxx\test.js:11:19 

通常对于asynchronous方法来说,没有太多可用的(有用的)堆栈跟踪。 像longjohn这样的模块可以帮助为这种方法提供更多的堆栈跟踪,但是由于其产生的开销,您不希望在生产中使用它。