0

So I have a directory with images: C:\Users\username\Desktop\mpimages

I need 1 random image to be uploaded then deleted from the folder.

This is the class which is clicked which brings up the file browser window to upload file < div class="om3e55n1" >

I've found this solution online but it's not working: fs.readdirSync is not a function.

const rnd = (arr) => arr[Math.floor(Math.random() * arr.length)];
const rndFile = () => `${dir}/${rnd(fs.readdirSync(dir))}`;

(async () => {
    const browser = await puppeteer.launch({headless: false});
    const page = await browser.newPage();
    await page.goto("YOUR/UPLOAD/URL")
    
  const file = rndFile();
  const elementHandle = await page.$("input[type=file]");
  await elementHandle.uploadFile(file);
  await page.click("input[type=submit]")
  
  fs.unlinkSync(file)
})();
Dresden21
  • 1
  • 2
  • Which version of node are you using? https://nodejs.org/api/fs.html#fsreaddirsyncpath-options the readdirSync API seems to be there since version 1 – Falital Sep 07 '22 at 13:59
  • I am on version 16.17.0 – Dresden21 Sep 07 '22 at 14:02
  • You probably overwrite fs somewhere before this code is run, when trying out something it is always better to simplify it as much as possible. Try the following code if it works my assumption is probably correct. const fs = require('fs'); let dir = __dirname const rnd = (arr) => arr[Math.floor(Math.random() * arr.length)]; const rndFile = () => `${dir}/${rnd(fs.readdirSync(dir))}`; const file = rndFile(); console.log(file) – Falital Sep 07 '22 at 14:08
  • Thank you seemed to work but now my other issue is: await elementHandle.uploadFile(file); ^ TypeError: Cannot read properties of null (reading 'uploadFile') – Dresden21 Sep 07 '22 at 14:22
  • This means the input you want to use could not be found by the puppeteer, so const elementHandle = await page.$("input[type=file]"); returns null see https://stackoverflow.com/questions/47966510/how-to-fill-an-input-field-using-puppeteer it might help – Falital Sep 07 '22 at 14:26
  • Thank you, I read that. This is weird because the selector I am using works. I've made it click separately to open the upload box and it does it every time. But when I add await elementHandle.uploadFile(file); it comes up with cannot read properties of null(reading 'Upload File). I'm new to this so there is definitely something wrong. – Dresden21 Sep 07 '22 at 15:16
  • Just wanted to say you've helped me out a lot. With a little more trial and error I was able to get it working successfully. I didn't know it has to be an input for the file upload. I thought any selector would work. – Dresden21 Sep 07 '22 at 15:41
  • No proplem happy to be of assistance, happy coding – Falital Sep 09 '22 at 13:10

0 Answers0