Reputation: 19193
I'm new to Node and server oriented code and am trying to get multiple svg files which are stored in the server.
Here is my code client-side using jQuery:
$.ajax({
url: someURL,
data: someData
})
.done(function(data) {
console.log('data got', data);
callback(null, data);
})
.fail(function() {
callback(new Error('Cannot access files'));
});
And here is my code server side:
// links is an array of links to the different svg files
var svgs = [];
async.eachSeries(links, function(link, next) {
fs.readFile(link, function(err, svg) {
svgs.push(svg);
next(err);
});
}, function(err) {
if (err) {
response.writeHead(500);
response.end(JSON.stringify(err));
return;
}
response.writeHead(200);
response.end(svgs); // Doesn't work
// response.end(svgs[0]); // Works
});
As long as I send only one file to the browser (which seem to be a Buffer instance), everything seems to work fine, but when I try to send multiple ones as an Array the transaction succeed but I got nothing in my returned data. That may be related to the MIME type of what I'm trying to send, but I couldn't find how to handle that.
Upvotes: 1
Views: 2469
Reputation: 123473
You'll have to convert svgs
into a String
or Buffer
first. One option is to stringify it as JSON:
response.writeHead(200, {
'Content-Type': 'application/json'
});
response.end(JSON.stringify(svgs));
This is because response.write()
, which response.end()
is calling to handle the data
(svgs
), doesn't accept Array
s.
chunk
can be a string or a buffer. Ifchunk
is a string, the second parameter specifies how to encode it into a byte stream. By default theencoding
is'utf8'
.
Whereas each svg
provided by fs.readFile()
is a Buffer
, so it has no issues writing svgs[0]
.
Upvotes: 2