Total Pageviews

2024/01/14

"errorMessage": "require is not defined in ES module scope, you can use import instead"

Problem

我在跟著 cloudguru 的 lab,學習如何寫一個簡單的 Node.js Lambda function


const https = require('https');
let url = "https://www.amazon.com";

exports.handler = async function(event) {
    let statusCode;
    await new Promise(function(resolve, reject) {
        https.get(url, (res) => {
            statusCode = res.statusCode;
            resolve(statusCode);
        }).on("error", (e) => {
            reject(Error(e));
        });
    });
    console.log(statusCode);
    return statusCode;
};

執行 Test Event 出現以下錯誤訊息
Test Event Name
MyTestEvent

Response
{
  "errorType": "ReferenceError",
  "errorMessage": "require is not defined in ES module scope, you can use import instead",
  "trace": [
    "ReferenceError: require is not defined in ES module scope, you can use import instead",
    "    at file:///var/task/index.mjs:1:15",
    "    at ModuleJob.run (node:internal/modules/esm/module_job:218:25)",
    "    at async ModuleLoader.import (node:internal/modules/esm/loader:329:24)",
    "    at async _tryAwaitImport (file:///var/runtime/index.mjs:1008:16)",
    "    at async _tryRequire (file:///var/runtime/index.mjs:1057:86)",
    "    at async _loadUserApp (file:///var/runtime/index.mjs:1081:16)",
    "    at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1119:21)",
    "    at async start (file:///var/runtime/index.mjs:1282:23)",
    "    at async file:///var/runtime/index.mjs:1288:1"
  ]
}

Root Cause

當您在 AWS Lambda 中使用 Node.js 20 版本,並且選擇使用 .mjs 附檔名時,Lambda 函數被視為 ES module。在 ECMAScript module 中,標準的 require 語法不能使用,因為它是 CommonJS 模塊系統的一部分,連帶上述 export 語法也需稍微改寫


Solution

程式碼需修改如下

import https from 'https';
let url = "https://www.amazon.com";

export async function handler(event) {
    let statusCode;
    await new Promise(function(resolve, reject) {
        https.get(url, (res) => {
            statusCode = res.statusCode;
            resolve(statusCode);
        }).on("error", (e) => {
            reject(Error(e));
        });
    });
    console.log(statusCode);
    return statusCode;
};


執行結果



2024/01/01

Unable to install mysqlclient package on EC2 instance (Amazon Linux 2023)

Problem

當我在建立 EC2 instance 時,輸入以下 bootstrap script 至 user data


#!/bin/bash  
yum update -y
yum install mysql -y

但是當啟動 EC2 後,使用 EC2 Instance Connect 進入後,輸入 mysql --version 卻出現以下錯誤訊息

mysql: command not found

經查啟動 log,發現 mysql client 安裝失敗

[ec2-user@ip-172-31-44-29 ~]$ cat /var/log/cloud-init-output.log
Last metadata expiration check: 0:00:03 ago on Mon Jan  1 04:21:12 2024.
No match for argument: mysql
Error: Unable to find a match: mysql
2024-01-01 04:21:15,423 - cc_scripts_user.py[WARNING]: Failed to run module scripts-user (scripts in /var/lib/cloud/instance/scripts)
2024-01-01 04:21:15,424 - util.py[WARNING]: Running module scripts-user (<module 'cloudinit.config.cc_scripts_user' from '/usr/lib/python3.9/site-packages/cloudinit/config/cc_scripts_user.py'>) failed
Cloud-init v. 22.2.2 finished at Mon, 01 Jan 2024 04:21:15 +0000. Datasource DataSourceEc2.  Up 32.23 seconds


Solution

經查因 Amazon Linux 2023 的內建套件與過往的 AMI 不同,需執行以下指令

# install pip (AL 2023 does not have one by default)
sudo dnf install -y pip

# install dependencies
sudo dnf install -y mariadb105-devel gcc python3-devel

# install mysqlclient
pip install mysqlclient


執行結果

   ,     #_
   ~\_  ####_        Amazon Linux 2023
  ~~  \_#####\
  ~~     \###|
  ~~       \#/ ___   https://aws.amazon.com/linux/amazon-linux-2023
   ~~       V~' '->
    ~~~         /
      ~~._.   _/
         _/ _/
       _/m/'
Last login: Mon Jan  1 04:24:46 2024 from 18.206.107.28
[ec2-user@ip-172-31-44-29 ~]$ mysql --version
mysql  Ver 8.0.35 for Linux on x86_64 (MySQL Community Server - GPL)


Increase/Decrease Font Size in iTerm2

Problem 
How to Increase/Decrease Font Size in iTerm2

How To
View => Make Text Bigger