- January 12, 2024
- Posted by: Vikas
- Category: NodeJs
Introduction:
As technology evolves, so do the tools and libraries that developers use to build applications. Amazon Web Services (AWS) constantly updates its SDKs to provide better features, improved performance, and enhanced security. If you’ve been using the AWS Node.js SDK for Node.js development purposes and are looking to transition from version 2 to version 3 for the getObject and putObject operations, you’re in the right place. In this guide, we’ll walk you through the necessary steps to smoothly migrate your code.
Why Upgrade to AWS SDK for Node.js v3?
AWS SDK for Node.js v3 brings several benefits, including improved modularity, better TypeScript support, and a more consistent API design in Node.js technology. Additionally, v3 introduces a more modular architecture, making it easier to install only the required components, reducing the overall size of your application bundle.
1. Install AWS SDK for JavaScript v3:
Update your project’s dependencies to include the latest version of the AWS SDK for JavaScript v3. You can install specific modules related to S3 to reduce the bundle size:
npm install @aws-sdk/client-s3
2. Update Import Statements:
Replace the import statements for AWS SDK v2 with the corresponding ones for v3. For example:
// Before
const AWS = require('aws-sdk');
// After
const { S3Client, GetObjectCommand, PutObjectCommand } = require(‘@aws-sdk/client-s3’);
3. Configure AWS SDK:
Configure the AWS SDK with your credentials and the AWS region. Update your configuration code accordingly:
// Before
AWS.config.update({
accessKeyId: 'your-access-key',
secretAccessKey: 'your-secret-key',
region: 'your-region',
});
// After
const client = new S3Client({ region: ‘your-region’ });
4. Refactor getObject and putObject Calls:
Adjust the syntax for getObject and putObject operations according to the new SDK version:
// Before
const s3 = new AWS.S3();
s3.getObject(params, (err, data) => {
if (err) console.error(err, err.stack);
else console.log(data);
});
// After
const command = new GetObjectCommand(params);
const response = await client.send(command);
console.log(response);
// Before
const s3 = new AWS.S3();
s3.putObject(params, (err, data) => {
if (err) console.error(err, err.stack);
else console.log(data);
});
// After
const command = new PutObjectCommand(params);
const response = await client.send(command);
console.log(response);
If you are reading a text file using the getObject method, in V3 now you need to use the transformToString method.
const response = await client.send(command);
// The Body object also has 'transformToByteArray' and 'transformToWebStream' methods.
const str = await response.Body.transformToString();