almost 5 years ago
我在上一篇文章最後,把我的node.js升級到0.12.0 (注意,Ubuntu的預設repo還在0.10.x版,所以如果你用apt-get install安裝的還會是舊版的)。
想要讓原本的專案正常運作,但發現失敗了
原來是fs的錯誤處理出問題
來看看以下Code吧
var fileStream = fs.createReadStream(localFilePath);
// ....省略...
fileStream.on('error', function(err) {
// 錯誤示範 Bad Example: do not use errno, use code instead
if (err.errno === 32) {
// 代表檔案或資料夾不存在 File not found
} else {
// 其他錯誤
}
});
其中,err.errno === 32
時,代表檔案不存在的錯誤(錯誤示範)
當時我第一次用Node.js時,自以為聰明,覺得數字判斷會比較快,於是特地使用 errno
。
沒想到我升級到Node.js v0.12.0時,這個errno卻變了!變成了 -2
!
於是就把檔案不存在判斷成其他錯誤了。在這裡應該使用err.code
來判斷才是正確的做法。
像是檔案不存在的錯誤,err.code
會是'ENOENT'
因此用err.code === 'ENOENT'
才是正確的做法。
才會確保多種node.js版本的相容性
var fileStream = fs.createReadStream(localFilePath);
// ....省略...
fileStream.on('error', function(err) {
if (err.code === 'ENOENT') {
// 代表檔案或資料夾不存在 File not found
} else {
// 其他錯誤 Other Errors
}
});