A bit baffled by this one. I'm using a pretty typical Node+Express setup, and many of my scripts are manipulating Buffer objects, which work fine basically everywhere. Except in one script, which defines a route for retrieving a document from an ElasticSearch data store. I'm trying to create a new Buffer object by decoding a base64-encoded string of the file data, and then send that to the browser. But even though a console.log immediately before the call to new Buffer(fildata,'base64')
prints out a description of the Buffer function just as you'd expect it to, I get an exception "TypeError: Buffer is not a function".
The relevant code:
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'));
And the output from node (note the console.log output just before the exception is thrown):
{ 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)
Reading your console output, the return value of require("buffer")
is not a function. Instead, it's an object that has two methods: Buffer
and SlowBuffer
.
In your case, Buffer
is that object with those two methods. You should instead do var Buffer = require('buffer').Buffer;
(assuming you don't also need SlowBuffer
).
As noted in another answer, you don't even need to require("buffer")
. It is automatically available as a global in Node.