1. /**
  2. * Attaches metadata to text files for sandbox usage with a timeout.
  3. *
  4. * @param {string} filePath The path to the text file.
  5. * @param {object} metadata The metadata to attach. Should be a plain JavaScript object.
  6. * @param {number} timeout The timeout in milliseconds.
  7. * @returns {Promise<boolean>} A promise that resolves if the metadata was attached successfully,
  8. * or rejects if an error occurred.
  9. */
  10. async function attachMetadataToTextFile(filePath, metadata, timeout) {
  11. return new Promise((resolve, reject) => {
  12. const startTime = Date.now();
  13. const fs = require('fs').promises; // Use promises-based fs API
  14. fs.readFile(filePath, 'utf-8')
  15. .then(fileContent => {
  16. // Construct the metadata string. Use a JSON string for simplicity.
  17. const metadataString = JSON.stringify(metadata);
  18. // Replace a placeholder in the file with the metadata string.
  19. const updatedContent = fileContent.replace(
  20. /METADATA_PLACEHOLDER/g, // Placeholder to denote where metadata will be inserted
  21. metadataString
  22. );
  23. // Write the updated content back to the file.
  24. return fs.writeFile(filePath, updatedContent, 'utf-8');
  25. })
  26. .then(() => {
  27. // File written successfully.
  28. resolve(true);
  29. })
  30. .catch(err => {
  31. // Handle file writing errors.
  32. console.error(`Error writing to file: ${err}`);
  33. reject(err);
  34. })
  35. .finally(() => {
  36. // Check for timeout.
  37. if (Date.now() - startTime > timeout) {
  38. console.warn('Metadata attachment timed out.');
  39. reject(new Error('Metadata attachment timed out.'));
  40. }
  41. });
  42. });
  43. }
  44. module.exports = attachMetadataToTextFile;

Add your comment