Write file with node - Error: ENOENT: no such file or directory

Hello, I need to create a kind of CDN that will store javascript files generated from copying another file with just a few modifications. The API will return the file path and it will be public to anyone who has the file URL. Websites will fetch this file.

This is the logic:

 const { id } = req.params

 const sourceDir = './public/scripts';
 const sourceFilename = 'script.js';
 const sourceFilePath = path.join(sourceDir, sourceFilename);
 const destFilename = `${id}.js`;
 const destFilePath = path.join(sourceDir, destFilename);

 try {
     if (!fs.existsSync(sourceDir)) {
         fs.mkdirSync(sourceDir, { recursive: true });
     }
     fs.copyFileSync(sourceFilePath, destFilePath);
     let jsContent = fs.readFileSync(destFilePath, 'utf8');
     const webhookUrl = `${process.env.BACKEND_URL}/api/webhook/${id}`;
     jsContent = jsContent.replace('PLACEHOLDER_WEBHOOK_URL', webhookUrl);
     jsContent = jsContent.replaceAll('PLACEHOLDER_ID', id);
     fs.writeFileSync(destFilePath, jsContent, 'utf8');
     res.status(200).json({ message: 'Successfully!' });

 } catch (error) {
     return res.status(500).json({ error });
 }

How to access the render directory system so that this occurs without error? How to copy the scripts file to the correct folder?

Error: ENOENT: no such file or directory, copyfile ‘public/scripts/script.js’ → ‘public/scripts/id32233233.js’

Hi there,

Where is public/scripts/script.js coming from? I don’t think this file exists in your service or isn’t in this location.

Please be mindful that if you want these copied files to exist after a restart you need to be writing them to a disk: https://docs.render.com/disks.

Regards,

Keith
Render Support, UTC+10 :australia:

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