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; };
執行結果