Creating files in /dist during build for Cloudflare Pages?

Hi everybody!

I am trying to retrieve files from a remote host and write them to the dist folder during the build process for Cloudflare Pages.

If the file already exists in the Git repository, e.g. ./dist/folder/file.html, I can write to that file and change its content using the below code:

async function downloadFile (url, filepath) {
    const res = await fetch(url);
    const fileStream = fs.createWriteStream(filepath);
    await new Promise((resolve, reject) => {
        res.body.pipe(fileStream);
        res.body.on("error", reject);
        fileStream.on("finish", resolve);
      });
  };

However, unfortunately, I haven’t figured out how to create a new file in ./dist/ to then write fetched content to. So far, I have tried fs.writeFile and fs-extra with ensureFile, but both quit with the same error:

ENOENT: no such file or directory

Is the dist folder writeable during build?

Any folder there should be writable. My guess is that your error is because the folder folder doesn’t exist.

2 Likes

@Cyb3r-Jak3, thank you, you assumed correctly! :slight_smile:

The build script can write to nonexistent files but only if the folder structure already exists.

If that’s not the case, the following code can create the required folder(s):

    if (!fs.existsSync(path.replace("/index.html", ""))){
      fs.mkdirSync(path.replace("/index.html", ""), { recursive: true });
    }

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.