How to parse a csv file from S3 and upload to S3 without keeping in a memory
Hi, I've never played before with streams and I may be lacking some in-depth understanding of streams in general. However, I would like to know how efficiently what I need should work.
I'm trying to get the csv file from S3 Bucket as a ReadableStream, parse it(e.g. add some test text to the headers), and upload it as a stream to S3 without keeping it in memory.
Here is my current implementation:
const objectStream = object?.Body as Readable | undefined;
if (objectStream === undefined) {
throw new Error('No data');
}
const transformationStream = new PassThrough();
const parserStream = parse({ headers: (headers) => headers.map((header) => header + 'TEST') })
.on('error', (error) => this.log.error(error))
.on('data', (row) => this.log.info(JSON.stringify(row)))
.on('end', (rowCount: number) => this.log.info(`Parsed ${rowCount} rows`));
objectStream.pipe(parserStream).pipe(transformationStream);
const upload = new Upload({
client: new S3Client(),
params: {
Bucket: bucketName,
Key: key,
Body: transformationStream,
},
});
await upload.done();
When trying to invoke that code I'm getting an error like the one below:
"The \"chunk\" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of Object",
"stack": "TypeError [ERR_INVALID_ARG_TYPE]: The \"chunk\" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of Object
at new NodeError (internal/errors.js:322:7)
at PassThrough.Writable.write (internal/streams/writable.js:285:13)
at uo.ondata (internal/streams/readable.js:731:22)
at uo.emit (events.js:412:35)
at uo.emit (/var/task/index.js:37:9384)
at addChunk (internal/streams/readable.js:293:12)
at readableAddChunk (internal/streams/readable.js:267:9)
at uo.Readable.push (internal/streams/readable.js:206:10)
at uo.Transform.push (internal/streams/transform.js:166:32)
at uo.pushRow (/var/task/index.js:37:11093)"
As far as I understood parserStream is not outputting string data.
When I drop out the pipe pipe(parserStream) the code works fine and the file has been uploading successfully to S3 but without expected transformation otherwise getting an error as above.
Basically, I'd like to know how to cope with that case, because I went through different solutions but any solution didn't help me out. I would be grateful for any advice. Thanks 🙌
Solved :)
Solved :)
How did you solve this? I have the same issue.
@ashley-jisc I had the same error when piping other stream to csv parser stream. Turns out you need to set objectMode: true when creating your stream, so it can accept any objects.
My code example:
const stream = fs.createReadStream(filePath);
const writableStream = new Writable({
objectMode: true,
write(chunk, encoding, next) {
console.log({chunk})
next();
}
});
await pipeline(stream, csv.parse({ headers: true }), writableStream);
For anyone still experiencing any problems with the AWS JavaScript SDK v3, I have an example to convert the object(s) output from the parse() method using another library to transfrom the object to a valid 'csv' string.
const { Upload } = require("@aws-sdk/lib-storage");
const { GetObjectCommand, S3Client } = require("@aws-sdk/client-s3");
const { parse } = require('fast-csv');
const { PassThrough } = require('stream');
const { stringify } = require('csv-stringify');
let Bucket = ""
let Key = ""
const client = new S3Client({
region: 'us-west-2',
credentials: {
accessKeyId: '',
secretAccessKey: ''
}
});
const getFile = async () => {
const obj = await client.send(new GetObjectCommand({
Bucket: Bucket,
Key: Key,
}));
const stream = await obj.Body;
return stream;
};
/** ------------------------------------------------------------------- */
const DoThings = async () => {
const Body = new PassThrough();
const s3Stream = await getFile();
const csv = parse({headers: true, objectMode:true})
.on('error', error => console.error(error))
.on('data', row => console.log(row))
.on('end', rowCount => console.log(`Parsed ${rowCount} rows`));
s3Stream.pipe(csv).pipe(stringify({header: true})).pipe(Body);
try {
const parallelUploads3 = new Upload({
client: client,
params: { Bucket, Key: 'upload-test.csv', Body },
tags: [],
// queueSize: 4, // (optional) concurrency configuration
// (optional) size of each part, in bytes, at least 5MB
partSize: 1024 * 1024 * 5,
leavePartsOnError: false,
});
parallelUploads3.on("httpUploadProgress", (progress) => {
console.log(progress);
});
await parallelUploads3.done();
} catch (e) {
console.log(e);
}
}
DoThings();