/**
* Attaches metadata to text files for sandbox usage with a timeout.
*
* @param {string} filePath The path to the text file.
* @param {object} metadata The metadata to attach. Should be a plain JavaScript object.
* @param {number} timeout The timeout in milliseconds.
* @returns {Promise<boolean>} A promise that resolves if the metadata was attached successfully,
* or rejects if an error occurred.
*/
async function attachMetadataToTextFile(filePath, metadata, timeout) {
return new Promise((resolve, reject) => {
const startTime = Date.now();
const fs = require('fs').promises; // Use promises-based fs API
fs.readFile(filePath, 'utf-8')
.then(fileContent => {
// Construct the metadata string. Use a JSON string for simplicity.
const metadataString = JSON.stringify(metadata);
// Replace a placeholder in the file with the metadata string.
const updatedContent = fileContent.replace(
/METADATA_PLACEHOLDER/g, // Placeholder to denote where metadata will be inserted
metadataString
);
// Write the updated content back to the file.
return fs.writeFile(filePath, updatedContent, 'utf-8');
})
.then(() => {
// File written successfully.
resolve(true);
})
.catch(err => {
// Handle file writing errors.
console.error(`Error writing to file: ${err}`);
reject(err);
})
.finally(() => {
// Check for timeout.
if (Date.now() - startTime > timeout) {
console.warn('Metadata attachment timed out.');
reject(new Error('Metadata attachment timed out.'));
}
});
});
}
module.exports = attachMetadataToTextFile;
Add your comment