NodeJS AWS Lambda:无法在模块外部使用import语句

xcitsw88  于 2023-03-22  发布在  Node.js
关注(0)|答案(1)|浏览(166)
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"
  ]
}

在向我的nodejs代码中添加前两行代码时出现此错误

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
    }
};

但是如果我删除这两行,我会得到错误消息cannot find module 'aws-sdk'
我想获取S3对象的内容。

yzuktlbb

yzuktlbb1#

尝试普通JS方式
const { createRequire } = require('module ');
而不是从“模块”导入{ createRequire };

**确保您已安装“模块”

相关问题