ill-bronzeI
Apify & Crawlee4y ago
5 replies
ill-bronze

Error: Cannot use import statement outside a module

Hello - I'm trying to use Apify to download a file.

I am following the tutorial here:

https://docs.apify.com/academy/puppeteer-playwright/common-use-cases/downloading-files

But I keep getting this error:

Error: Compilation of pageFunction failed.
2023-03-02T03:33:45.814Z   Cannot use import statement outside a module
2023-03-02T03:33:45.816Z       import fs from 'fs';
2023-03-02T03:33:45.818Z   SyntaxError: Cannot use import statement outside a module


My code:

async function pageFunction(context) {

    const { page, request, log } = context;

    import fs from 'fs';

    await page._client.send('Page.setDownloadBehavior', {behavior: 'allow', downloadPath: './my-downloads'})

    await page.click('span.dig-Button-content:contains("Download")');

    const fileNames = fs.readdirSync('./my-downloads');

    // Let's pick the first one
    const fileData = fs.readFileSync(`./my-downloads/${fileNames[0]}`);

    const base64PDF = Buffer.from(fileData).toString('base64');

    return {
        url: request.url,
        base64PDF: base64PDF
    };
}


Is the import statement supposed to go somewhere else? I'm using the code editor in the actor console. I've seen someone else mention putting
"type":"module"
in package.json, but I don't see anywhere to edit package.json in the actor console.

Can you LMK how to import fs, so I can read the downloaded file? Thank you!
Learn how to automatically download and save files to the disk using two of the most popular web automation libraries, Puppeteer and Playwright.
Downloading files | Apify Documentation
Was this page helpful?