AWS SDK - getObject convert returned file from ASCII buffer to json/csv

半世苍凉 提交于 2020-01-06 06:57:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!