How to Open a Local File in Puppeteer

Puppeteer can browser to more than just live websites. Learn how to easily open local files in Puppeteer.

How to Open a Local File in Puppeteer

There are countless ways to use Puppeteer for browser automation and testing. Although you will be navigating to live websites within the headless Chrome tool most of the time, you may find use cases where it makes sense to load in a local file instead. Here is how to open a local file in Puppeteer.

How to Open a Local File in Puppeteer

To open a local file in Puppeteer, change the navigation URL to the file directory location with the file:// prefix.

const puppeteer = require('puppeteer');

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    await page.goto(`file://${process.cwd()}/src/techozu.html`);

    //Do stuff here

   await browser.close();
})();
      
    

The file:// prefix replaces the standard http(s):// prefix and tells the browser to look for a local file. Since Puppeteer is essentially just headless Chrome, it will look and load the file in the location you specify. Your standard desktop browser will perform the same action. In fact, if you are unsure of the path for your file, you can drag the file into your browser window and then copy-paste the URL into Puppeteer.

For a Windows machine, your URL string will look something like this:

file:///C:/Users/Techozu/Projects/testfile.js
      
    

On Linux, it may look something like this:

file:///root/Projects/Techozu/scripts/testfile.js
      
    

In the code example above, we use the process.cwd() function to get the “Current Working Directory (cwd)” that we are running our script from. With that path available, we need to add any subdirectories and the file itself. Node automatically imports the “process” module, so no extra code is required to run that function. 

Why Open Local Files

One main reason for opening local files in Puppeteer is to create automated browser tests on your projects. With powerful testing frameworks like Jest, you can test simple websites without running a development server. You gain the ability to perform actions on your page as a user would and then use the “expect” function to verify that the page behaved as it should have. Other reasons to load a local file include automating the creation of specific file formats such as PDFs or images. 

We hope you found this guide helpful. For more useful Puppeteer tips, check out our Javascript section.