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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With