问题
I'm using the aws-sdk for Nodejs, and I'm getting an object back from AWS bucket in the form of a buffer, like so: [31, 139, 8, 0, 0, 0 ....]
The original object located in the bucket is in csv format, can I convert the buffer to a usable format like csv or json?
回答1:
You can do it easily, here's an example:
s3.getObject(params, function (error, data) {
if (error) {
throw error
} else {
// Convert the provided array to a string. You can save it as CSV if you want
const csvString = data.Body.toString('utf-8')
// Split the string into CSV lines
const csvLines = csvString.split(/\r|\n/)
// Iterate CSV lines
csvLines.forEach(line => {
// Extract CSV line values
const [ value1, value2, value3 ] = line.split(',')
// Do something with those values
console.log(value1, value2, value3)
})
}
})
回答2:
Assuming you have JSON in your S3 bucket. Heres a sample where you can read the JSON and parse it as an object
var options = {
BucketName : 'myBucket',
ObjectName : 'a/b/c.json',
ResponseContentType: 'application/json'
};
s3.getObject(options, function(err, data){
if (err){
console.log("Error: %s %s", err, err.stack);
}
else{
var fetchedObj = JSON.parse(data.Body.toString);
}
});
来源:https://stackoverflow.com/questions/49493311/aws-sdk-getobject-convert-returned-file-from-ascii-buffer-to-json-csv