__dirname is not defined in ES module scope In AWS Lambda Puppeteer

41 Views Asked by At
import * as fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import puppeteer from 'puppeteer-core';

const __filename = fileURLToPath(import.meta.url); // get the resolved path to the file
const __dirname = path.dirname(__filename); // get the name of the directory


export const handler = async (event: any) => {
    console.log(__dirname);
    console.log("Received event: " + JSON.stringify(event, null, 2));
    const htmlContent = event.htmlContent;
    console.log("event", event);
    console.log("htmlContent", htmlContent);
    const pdfFileName = generatePDFFileName();

    try {
        const browser = await puppeteer.launch();
        const page = await browser.newPage();
        await browser.close();
    } catch (error) {
        console.error('Error generating PDF:', error);
        throw new Error('Error generating PDF');
    }
};

this is our lambda code ,using puppeteer-core : 22.3.0 node 20x

But still this gives

"ReferenceError: __dirname is not defined in ES module scope",
        "    at node_modules/yargs/build/index.cjs (/node_modules/yargs/build/index.cjs:1:61388)",
        "    at __require2 (file:///var/task/generatePdf.mjs:20:50)",
        "    at <anonymous> (/node_modules/yargs/yargs.mjs:3:17)",
        "    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)"
    ]

Anything you feel i am doing wrong here ?? want to generate a pdf but this initialization itself fails

0

There are 0 best solutions below