Skip to content

[🐛 Bug]: Cannot download file with Javascript. WebDriverError: Cannot find file [xxx] in directory xxxx #14111

@limuyuan

Description

@limuyuan

What happened?

When I'm trying to download a file with Javascript driver.downloadFile, it always return error message that the downloaded file cannot be found, but I did find the downloaded file in the same folder as expected.

How can we reproduce the issue?

Exception will be thrown after executing await driver.downloadFile(files, targetDirectory);

const webdriver = require("selenium-webdriver");
const path = require('path');
const os = require('os');
const { By } = webdriver;
const firefox = require('selenium-webdriver/firefox');
const options = new firefox.Options()

async function runTest_DownloadFile() {
  try {
    options.set('se:downloadsEnabled', true);

    let driver = new webdriver.Builder()
    .usingServer("http://192.168.0.116:4444")
    .forBrowser("firefox")
    .setFirefoxOptions(options)
    .build()

    const fileNames = ['20MB.bin'];

    driver.get("https://myjob.page/tools/test-files").then(async () => {
      downloadLink = await driver.findElement(By.xpath('/html/body/main/div/div/div[1]/a[5]'));
      await downloadLink.click();

      await waitForDownloadableFile(driver, fileNames);
      files = await driver.getDownloadableFiles();

      if (files.sort().toString() === fileNames.sort().toString()) {
        console.log(JSON.stringify({ status: "passed", message: "Test passed successfully" }));
      } else {
        console.log(JSON.stringify({ status: 'failed', message: 'Files mismatch!' }));
      }

      const targetDirectory = path.join(os.tmpdir(), 'nodejs_downloaded');
      await driver.downloadFile(files, targetDirectory);

      try {
        await driver.quit();
      } catch (error) {
        if (error.message != "success") {
          console.error('Error during test execution:', error);
          console.log(JSON.stringify({ status: "failed", message: error.message }));
        }
      }
      console.log(JSON.stringify({ status: "passed", message: "Test passed successfully" }));
    });
  } catch (error) {
    if (driver) {
      await driver.quit();
    }
    console.error('Error during test execution:', error);
    console.log(JSON.stringify({ status: "failed", message: error.message }));
  }
}

// Function to wait for downloadable files to include the desired file
async function waitForDownloadableFile(driver, fileNames, interval = 3000, maxAttempts = 10) {
  let attempt = 0;
  while (attempt < maxAttempts) {
    const files = await driver.getDownloadableFiles();
    if (fileNames.every(fileName => files.includes(fileName))) {
      return;
    }
    await new Promise(resolve => setTimeout(resolve, interval));
    attempt++;
  }
  throw new Error(`Timeout: Files '${fileNames}' not found after ${maxAttempts} attempts`);
}

runTest_DownloadFile();

Relevant log output

Uncaught WebDriverError WebDriverError: Cannot find file [[20MB.bin]] in directory C:\Users\morris\AppData\Local\Temp\uuid13450316481929214739243743f-a595-442a-a00c-628ac48d6152\download4510867298970579268.
Build info: version: '4.21.0', revision: '79ed462ef4'
System info: os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '17.0.5'
Driver info: driver.version: unknown
    at throwDecodedError (d:\GitHub\Li-MuYuan\Selenium-Scripts\node-js\node_modules\selenium-webdriver\lib\error.js:521:15)
    at parseHttpResponse (d:\GitHub\Li-MuYuan\Selenium-Scripts\node-js\node_modules\selenium-webdriver\lib\http.js:514:13)
    at execute (d:\GitHub\Li-MuYuan\Selenium-Scripts\node-js\node_modules\selenium-webdriver\lib\http.js:446:28)
    at processTicksAndRejections (internal/process/task_queues:95:5)

Operating System

Windows 10

Selenium version

Selenium 4.21.0

What are the browser(s) and version(s) where you see this issue?

Firefox 126

What are the browser driver(s) and version(s) where you see this issue?

Gecko Driver 0.34.0

Are you using Selenium Grid?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-nodejsJavaScript BindingsJ-awaiting answerQuestion asked of user; a reply moves it to triage again

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions