0
Response
{
  "errorType": "Runtime.UserCodeSyntaxError",
  "errorMessage": "SyntaxError: Cannot use import statement outside a module",
  "trace": [
    "Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module",
    "    at _loadUserApp (file:///var/runtime/index.mjs:993:17)",
    "    at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1031:21)",
    "    at async start (file:///var/runtime/index.mjs:1194:23)",
    "    at async file:///var/runtime/index.mjs:1200:1"
  ]
}

Getting this error when adding this first two lines of code to my nodejs code

import { createRequire } from 'module';
const require = createRequire(import.meta.url)

const AWS = require('aws-sdk');
const s3 = new AWS.S3();

exports.handler = async (event) => {
    const bucketName = 'your-bucket-name';
    const objectKey = 'your-object-key';

    const params = {
        Bucket: bucketName,
        Key: objectKey
    };

    try {
        const data = await s3.getObject(params).promise();
        const objectContent = data.Body.toString('utf-8');
        console.log(objectContent);
        // Do something with the object content
    } catch (err) {
        console.log(err);
        // Handle error
    }
};

but if I remove that 2 lines I get error saying cannot find module 'aws-sdk'.

I want to get the content of the S3 object.

John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
  • Does this answer your question? ["Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6](https://stackoverflow.com/questions/58211880/uncaught-syntaxerror-cannot-use-import-statement-outside-a-module-when-import) – devpolo Mar 16 '23 at 07:34

1 Answers1

0

Try commonJS way

const { createRequire } = require('module');

instead of import { createRequire } from 'module';

** make sure that you have installed "module"