我确信我遗漏了一些明显的东西,但问题的要点是我从Mapbox调用接收到一个PNG,意图将其写入文件系统并将其提供给客户端。我已经成功地转发了调用,收到了原始数据的响应,并写入了一个文件。问题是,无论我采用什么路径,我的文件最终都会被截断,而且我已经用尽了我找到的绕过这个主题的答案。我已经转储了对日志的原始响应,而且它很健壮,但我创建的任何文件往往都是一大块不可读的数据。
这是我目前用来制作文件的代码。在几次失败和相对徒劳无功的迭代之后,我尝试了这种缓冲区移动作为最后的尝试。任何帮助都将不胜感激。
module.exports = function(req, res, cb) {
var cartography = function() {
return https.get({
hostname: 'api.mapbox.com',
path: '/v4/mapbox.wheatpaste/' + req.body[0] + ',' + req.body[1] + ',6/750x350.png?access_token=' + process.env.MAPBOX_API
}, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
var mapPath = 'map' + req.body[0] + req.body[1] + '.png';
var map = new Buffer(body, 'base64');
fs.writeFile(__dirname + '/client/images/maps/' + mapPath, map, 'base64', function(err) {
if (err) throw err;
cb(mapPath);
})
})
});
};
cartography();
};发布于 2016-09-02 20:48:49
可以在更紧凑的子例程中重写代码:
const fs = require('fs');
const https = require('https');
https.get(url, (response)=> { //request itself
if(response) {
let imageName = 'image.png'; // for this purpose I usually use crypto
response.pipe( //pipe response to a write stream (file)
fs.createWriteStream( //create write stream
'./public/' + imageName //create a file with name image.png
)
);
return imageName; //if public folder is set as default in app.js
} else {
return false;
}
})您可以从url获取原始名称和扩展名,但使用crypto生成新名称并获取文件扩展名更安全,就像我从url或read-chunk和file-type模块中所说的那样。
https://stackoverflow.com/questions/39286407
复制相似问题