使用Lambda / S3逐行读取文件

时间:2018-10-12 18:58:39

标签: node.js amazon-s3 aws-lambda aws-sdk

我想逐行读取S3上的文件。我尝试了以下代码,这些代码是我在网上搜索到的,但是Lambda函数正在退出而未调用任何readline回调。我在做什么错了?

const aws = require('aws-sdk');
const s3 = new aws.S3({ apiVersion: '2006-03-01' });
const readline = require('readline');

exports.handler = async (event, context, callback) => {
    const bucket = event.Records[0].s3.bucket.name;
    const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
    const params = {
        Bucket: bucket,
        Key: key,
    };

    const s3ReadStream = s3.getObject(params).createReadStream();

    const rl = readline.createInterface({
      input: s3ReadStream,
      terminal: false
    });

    rl.on('line', (line) => {
      console.log(`Line from file: ${line}`);
    });
    rl.on('error', () => {
        console.log('error');
    });
    rl.on('close', function () {
        console.log('closed');
        context.succeed();
    });
    console.log('done');
};

2 个答案:

答案 0 :(得分:6)

我发现了问题。一段时间以来,我还没有在Lambda上进行编码,我认为只有在调用上下文时它才会退出。我现在正在等待诺言被兑现(或被拒绝,稍后再执行)。

package application;

import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

public class Persona {



    private StringProperty nombres;
    private StringProperty apellidos;
    private IntegerProperty id_cliente;

public Persona ( String nombres, String apellidos, Integer id_cliente) {
    this.nombres=  new SimpleStringProperty (nombres);
    this.apellidos= new SimpleStringProperty ( apellidos);
    this.id_cliente=new SimpleIntegerProperty (id_cliente);
}




public String getNombres() {
    return nombres.get();
}

public  void  setNombres(String nombres) {
    this.nombres=new SimpleStringProperty (nombres);
}


public String getApellidos() {
    return apellidos.get();
}

public  void  setApellidos(String apellidos) {
    this.apellidos=new SimpleStringProperty ( apellidos);
}


public Integer getId_cliente() {
    return id_cliente.get();
}

public  void  setid_cliente(Integer id_cliente) {
    this.id_cliente=new SimpleIntegerProperty (id_cliente);
}

}

答案 1 :(得分:0)

getObject不仅返回存储了S3的对象。它返回一个JSON对象,其Body字段保存存储到S3的对象的Blob。另请参见文档hereResponse部分。