我對JavaScript和Node JS真的很陌生。我有我想要緩衝的各種圖像URL。我已經嘗試了請求npm模塊,但想要實現我想要的更低級別的庫。如何使用本機Node JS HTTP庫將圖像寫入緩衝區?
我看到很多examples使用request module或實例的文件保存到磁盤建議。但是,我找不到一個簡單緩衝圖像的HTTP GET請求示例,所以我可以傳遞給另一個函數。它需要有一個「結束」事件,所以我可以在另一個步驟中放心地上傳緩存的圖像數據。有人可以提供樣本模式或「如何」嗎?謝謝!
我對JavaScript和Node JS真的很陌生。我有我想要緩衝的各種圖像URL。我已經嘗試了請求npm模塊,但想要實現我想要的更低級別的庫。如何使用本機Node JS HTTP庫將圖像寫入緩衝區?
我看到很多examples使用request module或實例的文件保存到磁盤建議。但是,我找不到一個簡單緩衝圖像的HTTP GET請求示例,所以我可以傳遞給另一個函數。它需要有一個「結束」事件,所以我可以在另一個步驟中放心地上傳緩存的圖像數據。有人可以提供樣本模式或「如何」嗎?謝謝!
這是土辦法:(二進制響應encoding:null
)
var http=require('http'), imageBuffer;
http.get(
'http://www.kame.net/img/kame-anime-small.gif',
function(res) {
var body=new Buffer(0);
if (res.statusCode!==200) {
return console.error('HTTP '+res.statusCode);
}
res.on('data', function(chunk) {
body=Buffer.concat([body, chunk]);
});
res.on('end', function() {
imageBuffer=body;
});
res.on('error', function(err) {
console.error(err);
});
}
);
// Small webserver serving the image at http://127.0.0.1:4567
http.createServer(function(req, res) {
res.write(imageBuffer || 'Please reload page');
res.end();
}).listen(4567, '127.0.0.1');
和使用要求:
var request=require('request'), imageBuffer;
request({
uri: 'http://www.kame.net/img/kame-anime-small.gif',
encoding: null
}, function(err, res, body) {
if (err) {
return console.error(err);
} else if (res.statusCode!==200) {
return console.error('HTTP '+res.statusCode);
}
imageBuffer=body;
});
// Small webserver serving the image at http://127.0.0.1:4567
require('http').createServer(function(req, res) {
res.write(imageBuffer || 'Please reload page');
res.end();
}).listen(4567, '127.0.0.1');
下面是使用一個簡單的例子內置的流式HTTP響應有:
var http = require('http');
var fs = require('fs');
var file = fs.createWriteStream("test.png");
var request = http.get("some URL to an image", function(response) {
response.pipe(file);
});
I ra自己併成功從外部網站下載圖像並將其保存到文件中,然後將該文件加載到瀏覽器中以查看相同的圖像。
這是否也適用於本機HTTPS請求?我可以使用本地'https'庫同時獲得'http'和'https'請求嗎?換句話說,我可以將'http' URLs傳遞給'https'library嗎? – filmplane