如何从Node.js中的S3 getObject获得响应? [英] How to get response from S3 getObject in Node.js?
问题描述
在Node.js项目中,我试图从S3取回数据.
In a Node.js project I am attempting to get data back from S3.
当我使用getSignedURL
时,一切正常:
When I use getSignedURL
, everything works:
aws.getSignedUrl('getObject', params, function(err, url){
console.log(url);
});
我的参数是:
var params = {
Bucket: "test-aws-imagery",
Key: "TILES/Level4/A3_B3_C2/A5_B67_C59_Tiles.par"
如果我将URL输出带到控制台并将其粘贴到Web浏览器中,它将下载所需的文件.
If I take the URL output to the console and paste it in a web browser, it downloads the file I need.
但是,如果我尝试使用getObject
,我会得到各种各样的奇怪行为.我相信我只是在错误地使用它.这是我尝试过的:
However, if I try to use getObject
I get all sorts of odd behavior. I believe I am just using it incorrectly. This is what I've tried:
aws.getObject(params, function(err, data){
console.log(data);
console.log(err);
});
输出:
{
AcceptRanges: 'bytes',
LastModified: 'Wed, 06 Apr 2016 20:04:02 GMT',
ContentLength: '1602862',
ETag: '9826l1e5725fbd52l88ge3f5v0c123a4"',
ContentType: 'application/octet-stream',
Metadata: {},
Body: <Buffer 01 00 00 00 ... > }
null
因此,这似乎正常工作.但是,当我在console.log
之一上放置一个断点时,我的IDE(NetBeans)会引发错误并拒绝显示数据值.尽管这可能只是IDE,但我还是决定尝试其他使用getObject
的方法.
So it appears that this is working properly. However, when I put a breakpoint on one of the console.log
s, my IDE (NetBeans) throws an error and refuses to show the value of data. While this could just be the IDE, I decided to try other ways to use getObject
.
aws.getObject(params).on('httpData', function(chunk){
console.log(chunk);
}).on('httpDone', function(data){
console.log(data);
});
这不会输出任何内容.放置断点表明代码永远不会到达console.log
之一.我也尝试过:
This does not output anything. Putting a breakpoint in shows that the code never reaches either of the console.log
s. I also tried:
aws.getObject(params).on('success', function(data){
console.log(data);
});
但是,这也不会输出任何内容,并且放置断点表明console.log
永远不会到达.
However, this also does not output anything and placing a breakpoint shows that the console.log
is never reached.
我在做什么错了?
推荐答案
When doing a getObject()
from the S3 API, per the docs the contents of your file are located in the Body
property, which you can see from your sample output. You should have code that looks something like the following
const aws = require('aws-sdk');
const s3 = new aws.S3(); // Pass in opts to S3 if necessary
var getParams = {
Bucket: 'abc', // your bucket name,
Key: 'abc.txt' // path to the object you're looking for
}
s3.getObject(getParams, function(err, data) {
// Handle any error and exit
if (err)
return err;
// No error happened
// Convert Body from a Buffer to a String
let objectData = data.Body.toString('utf-8'); // Use the encoding necessary
});
您可能不需要从data.Body
对象创建新的缓冲区,但是如果需要,可以使用上面的示例来实现.
You may not need to create a new buffer from the data.Body
object but if you need you can use the sample above to achieve that.
这篇关于如何从Node.js中的S3 getObject获得响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!