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.
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.
Share Improve this question asked Sep 28, 2018 at 10:51 user3130478user3130478 2171 gold badge4 silver badges12 bronze badges 1- what do you mean "add a timestamp". Add it where? On the filename? Inside the file? Something else? Please be clear about your requirement. P.S. Is this NodeJS? Please tag it appropriately if so. – ADyson Commented Sep 28, 2018 at 11:02
1 Answer
Reset to default 15Date.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