top of page

Quick Tip: Unique Date/Time in a test file with JavaScript

Sometimes, you need to make a test file unique. Maybe duplicates get rejected! So why not use a timestamp and replace a placeholder in your file?


If this applies to you, you're in luck, as I'm about to explain how to do it in TypeScript!


You've got a text file like this:

Report generated at: {{date/time}}

And you want to replace {{date/time}} with the current date and time.

Then you need this little bit of code:


import { readFileSync, writeFileSync } from 'fs';

// Read the original file
const filePath = 'output/report.txt';
const content = readFileSync(filePath, 'utf-8');

// Generate current timestamp
const timestamp = new Date().toISOString();

// Replace the placeholder
const updatedContent = content.replace('{{date/time}}', timestamp);

// Write it back to the file (overwrite)
writeFileSync(filePath, updatedContent);

console.log('Placeholder replaced with timestamp.');

So what are we doing?

  • readFileSync() loads the file content

  • replace() finds and swaps the {{date/time}} string

  • writeFileSync() saves the updated content back to the file


An important point: make sure the text you are replacing only exists where you want it replaced. Sounds simple, but misnaming could cause chaos, hence the double curly brackets!


And if you want to make it reusable, make it a function:

export function replacePlaceholderWithDate(filePath: string, placeholder = '{{date/time}}') {
  const content = readFileSync(filePath, 'utf-8');
  const timestamp = new Date().toISOString();
  const updated = content.replace(placeholder, timestamp);
  writeFileSync(filePath, updated);
}

Then you can call it with:

replacePlaceholderWithDate('output/report.txt');

And there we are! Simple, dynamic and unique files.


This can be used for many cases - it doesn't just have to be dates!

 
 
 

Recent Posts

See All

Comments


bottom of page