有點困惑這個。我正在使用一個非常典型的Node + Express設置,並且我的許多腳本都在操作Buffer對象,這些對象基本上在任何地方都能正常工作。除了一個腳本,它定義了從ElasticSearch數據存儲中檢索文檔的路徑。我試圖通過解碼base64編碼的文件數據字符串來創建一個新的Buffer對象,然後將其發送給瀏覽器。但即使調用new Buffer(fildata,'base64')
之前的console.log會按照您所期望的打印出Buffer函數的說明,但我會遇到一個異常「TypeError:Buffer不是函數」。NodeJS:TypeError:緩衝區不是一個函數(但它是一個函數!)
相關的代碼:
var Buffer = require('buffer');
// ... then in the route, inside the callback from the ElasticSearch get() method:
res.setHeader('Content-Type', doc["mimetype"]);
res.setHeader('Content-disposition', 'attachment; filename=' + doc["filename"]);
res.type(doc["mimetype"]);
console.log(Buffer); // Yep, definitely a function here!
res.send(new Buffer(doc["filedata"], 'base64'));
而且從節點的輸出(注意的console.log輸出的異常被拋出之前):
{ Buffer:
{ [Function: Buffer]
poolSize: 8192,
isBuffer: [Function: isBuffer],
compare: [Function: compare],
isEncoding: [Function],
concat: [Function],
byteLength: [Function: byteLength] },
SlowBuffer: [Function: SlowBuffer],
INSPECT_MAX_BYTES: 50,
kMaxLength: 2147483647 }
/Users/myusername/mynodeproject/routes/retrieve.js:50
res.send(new Buffer(doc["filedata"], 'base64'));
^
TypeError: Buffer is not a function
at /Users/myusername/mynodeproject/routes/retrieve.js:50:15
at respond (/Users/myusername/mynodeproject/node_modules/elasticsearch/src/lib/transport.js:301:9)
at checkRespForFailure (/Users/myusername/mynodeproject/node_modules/elasticsearch/src/lib/transport.js:239:7)
at HttpConnector.<anonymous> (/Users/myusername/mynodeproject/node_modules/elasticsearch/src/lib/connectors/http.js:155:7)
at IncomingMessage.wrapper (/Users/myusername/mynodeproject/node_modules/lodash/index.js:3095:19)
at emitNone (events.js:72:20)
at IncomingMessage.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:905:12)
at doNTCallback2 (node.js:452:9)
at process._tickCallback (node.js:366:17)
D'oh!是的,顯然今天早上我需要更多的咖啡!謝謝。 – DanM