There are a lot of ways to test and automate browsers with Puppeteer. Most of the time, you will use the headless Chrome tool to navigate to live websites.
However, there may be times when it makes sense to load a local file instead. Here’s how to use Puppeteer to open a local file.
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 usual http(s):// prefix and tells the browser to look for a local file. Since Puppeteer is just Chrome without a user interface, it will look for the file in the place you tell it to.
The same thing will happen with your regular desktop browser. If you don’t know where your file is located, you can drag it into your browser window and then copy and paste the URL into Puppeteer.
On a Windows computer, 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 find out where our script is running from.
Now that we have the path, we need to add any subdirectories and the file itself. The “process” module is automatically imported by Node, so you don’t need extra code to run that function.
Why Open Local Files
When you open local files in Puppeteer, one of the main reasons is to make automated browser tests for your projects. You can test simple websites without running a development server if you use a robust testing framework like Jest.
You can do things on your page as a user would, and then use the “expect” function to make sure the page did what it was supposed to. Another reason to load a local file is to automatically make certain file types, like PDFs or images.