AWS Lambda使用NodeJS读取文件

时间:2019-07-02 14:28:28

标签: node.js amazon-web-services aws-lambda

我尝试创建一个lambda函数来发送电子邮件。问题是我无法在Lambda上获取电子邮件模板路径。我收到的错误是:

  

“ errorMessage”:“ ENOENT:没有这样的文件或目录,请打开'/var/task/email_template.ejs'”

这是我的项目结构和代码: Project structure

service.js:

export const generateEmail = async (subject, text, email) => {
  try {
    const pathName = process.env.LAMBDA_TASK_ROOT
      ? path.resolve(process.env.LAMBDA_TASK_ROOT, 'email_template.ejs')
      : path.resolve(__dirname, 'email_template.ejs')

    const data = await ejs.renderFile(pathName, {
      name: 'John Doe'
    })

    return {
      from: '"Service" <no-reply.service@ses.com>',
      to: email,
      subject: subject,
      text: text,
      html: data
    }
  } catch (err) {
    throw err
  }
}

sendMail.js

exports.handler = async (event, context, callback) => {
  if (event.httpMethod === 'POST' && event.body) {
    const req = JSON.parse(event.body)
    const { name, email } = req

    if (!email.match(/^[^@]+@[^@]+$/)) {
      console.log('Not sending: invalid email address', body.email)
      return callback(null, {
        statusCode: 400,
        body: JSON.stringify({
          error_code: 'invalid_email',
          message: 'Cannot send. Your email is invalid'
        })
      })
    }

    const config = {
      accessKeyId: process.env.ACCESS_KEY,
      secretAccessKey: process.env.SECRET_KEY
    }

    const transporter = nodemailer.createTransport(ses(config))
    const mailOptions = await generateEmail('Hello ✔', 'Hello world', email)

    try {
      await transporter.sendMail(mailOptions)
      return callback(null, {
        statusCode: 204
      })
    } catch (err) {
      return callback(null, {
        statusCode: 400,
        body: JSON.stringify({
          error_code: 'general_error',
          message: 'Please try again later',
          full_error: err
        })
      })
    }
  }

  return callback(null, {
    statusCode: 400,
    body: JSON.stringify({
      error_code: 'missing_parameters',
      message: 'Please provide your name and email'
    })
  })
}

generateEmail函数在本地完美运行,但不适用于lambda函数。

任何帮助将不胜感激,谢谢!

1 个答案:

答案 0 :(得分:1)

我终于找到了答案。 原因是因为在webpack构建时,它会忽略我的email_template.ejs文件。

因此,我将此行添加到webpack.config.js中,以使其存在于zip输出中,并且效果很好。

 uri_duration = 90
 s3Client = boto3.client('s3')
 url = s3Client.generate_presigned_url('get_object', Params = 
 {'Bucket': bucket, 
 'Key': filekey'}, ExpiresIn = uri_duration)