[英]How to read CSV data from S3 using Node.js AWS Lambda function
I have a Node.js AWS Lambda function and I am trying to read records from a CSV file in S3 and print its contents.我有一个 Node.js AWS Lambda function 并且我正在尝试从 ZCC8D68C551C4A9A6D5313E 中的 ZCC8D68C551C4A9A6D5313E 文件中读取记录并打印其内容。
Below is my code to achieve the same however I am getting Null as output.下面是我实现相同的代码,但是我得到 Null 为 output。
Code:代码:
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const csv = require('csv-parser');
const bucket = 'awslambdabuckets';
const objectkey = 'record.csv';
const params = { Bucket: bucket, Key: objectkey };
const results = [];
exports.handler = async function (event, ctx, callback) {
try {
const file = s3.getObject(params).createReadStream();
file
.pipe(csv())
.on('data', function (data) {
results.push;
})
.on('end', () => {
console.log(results);
callback(null, results);
});
} catch (err) {
console.log(err);
callback(Error(err));
}
};
Can someone help me point out what's the problem and how to fix it.有人可以帮我指出问题所在以及如何解决。
You are not pushing the data to the result, see and make changes as below您没有将数据推送到结果,请查看并进行如下更改
exports.handler = async function (event, ctx, callback) {
try {
const file = s3.getObject(params).createReadStream();
file
.pipe(csv())
.on('data', function (data) {
results.push(data);
})
.on('end', () => {
console.log(results);
callback(null, results);
});
} catch (err) {
console.log(err);
callback(Error(err));
}
};
You are not pushing data to the array:您没有将数据推送到数组:
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const csv = require('csv-parser');
const bucket = 'awslambdabuckets';
const objectkey = 'record.csv';
const params = { Bucket: bucket, Key: objectkey };
const results = [];
exports.handler = function (event, ctx, callback) {
try {
const file = s3.getObject(params).createReadStream();
file
.pipe(csv())
.on('data', function (data) {
results.push(data); // --> here
})
.on('end', () => {
console.log(results);
callback(null, results);
});
} catch (err) {
console.log(err);
callback(Error(err));
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.