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’