Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timestamp in file name JS

I want to add a time stamp to a XML file while it's copy from location A to B.

const fs = require('fs');

// destination.txt will be created or overwritten by default.
fs.copyFile('\\\\IP\\FOLDER\\FILE.xml', 'c:\\FOLDER\\FILE.xml', (err) => {
  if (err) throw err;
  console.log('OK! Copy FILE.xml');
});

The copy works, but I have no idea how to add the time stamp.

like image 201
user3130478 Avatar asked Sep 28 '18 10:09

user3130478


1 Answers

Date.now gives you a time stamp (i.e. the number elapsed of milliseconds since 1 Jan 1970).

You can add it to the second argument for copyFile, which is the destination path an file name.

Example:

const fs = require('fs');

// destination.txt will be created or overwritten by default.
fs.copyFile('\\\\IP\\FOLDER\\FILE.xml', `c:\\FOLDER\\FILE_${Date.now()}.xml`, (err) => {
  if (err) throw err;
  console.log('OK! Copy FILE.xml');
});

Note the back ticks – that's a JavaScript template string that allows you to add data using ${}.

If you need a date string of the current day, as you pointed out in the comments, you can write a little helper function that creates this string:

const fs = require('fs');

function getDateString() {
  const date = new Date();
  const year = date.getFullYear();
  const month = `${date.getMonth() + 1}`.padStart(2, '0');
  const day =`${date.getDate()}`.padStart(2, '0');
  return `${year}${month}${day}`
}

// destination.txt will be created or overwritten by default.
fs.copyFile('\\\\IP\\FOLDER\\FILE.xml', `c:\\FOLDER\\FILE_${getDateString()}.xml`, (err) => {
  if (err) throw err;
  console.log('OK! Copy FILE.xml');
});

This will create a file name like this: FILE_20182809.xml

like image 65
Patrick Hund Avatar answered Sep 20 '22 18:09

Patrick Hund